---
title: "Write a Rust program to check if a string is an anagram of another string."  
description: "Write a Rust program to check if a string is an anagram of another string."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-24  
canonical: https://www.mindstick.com/forum/158804/write-a-rust-program-to-check-if-a-string-is-an-anagram-of-another-string  
category: "rust"  
tags: ["string", "programs", "rust"]  
reading_time: 2 minutes  

---

# Write a Rust program to check if a string is an anagram of another string.

Write a [Rust](https://www.mindstick.com/forum/160170/explain-rust-s-ownership-borrowing-and-lifetimes-system) [program to check](https://www.mindstick.com/forum/157542/write-a-java-program-to-check-if-a-list-of-integers-contains-only-odd-numbers) if a [string is an anagram](https://www.mindstick.com/forum/158768/write-a-python-program-to-check-if-a-string-is-an-anagram-of-another-string) of another string.

## Replies

### Reply by Aryan Kumar

Rust

```plaintext
fn is_anagram(str1: &str, str2: &str) -> bool {
  // Check if the two strings have the same length.
  if str1.len() != str2.len() {
    return false;
  }

  // Create a vector of characters for each string.
  let mut char_counts1 = Vec::new();
  let mut char_counts2 = Vec::new();
  for c in str1.chars() {
    char_counts1.push(c);
  }
  for c in str2.chars() {
    char_counts2.push(c);
  }

  // Sort the two vectors of characters.
  char_counts1.sort();
  char_counts2.sort();

  // Check if the two vectors are equal.
  for i in 0..char_counts1.len() {
    if char_counts1[i] != char_counts2[i] {
      return false;
    }
  }

  // The two strings are anagrams.
  return true;
}

fn main() {
  let str1 = "hello";
  let str2 = "olleh";

  let is_anagram = is_anagram(str1, str2);
  println!("The strings are anagrams: {}", is_anagram);
}
```

This [program](https://www.mindstick.com/blog/12337/scaling-up-your-mentorship-program) first checks if the two strings have the same length. If they do, then the program creates two vectors of characters, one for each [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp). The characters in each vector are then sorted. Finally, the two vectors are compared to see if they are equal. If they are equal, then the two strings are anagrams.

To run this program, you can save it as a .rs file and then compile and run it using the following commands:

Code snippet

```plaintext
rustc anagram.rs
./anagram
```

This will print the following output:

Code snippet

```plaintext
The strings are anagrams: true
```

This indicates that the two strings hello and olleh are anagrams.


---

Original Source: https://www.mindstick.com/forum/158804/write-a-rust-program-to-check-if-a-string-is-an-anagram-of-another-string

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
