Rust Program to Check if two strings are anagram


Check if two strings are anagram

Rust Programming Language


Check if two strings are anagram


Problem


In Rust, we can check if two strings are anagrams by comparing the sorted versions of each string. If the sorted versions are the same, then the strings are anagrams. Here's an example program that demonstrates how to do this.

Input


fn is_anagram(str1: &str, str2: &str) -> bool {
    let sorted_str1 = sort_string(str1);
    let sorted_str2 = sort_string(str2);

    sorted_str1 == sorted_str2
}

fn sort_string(str: &str) -> String {
    let mut chars: Vec<char> = str.chars().collect();
    chars.sort();
    chars.into_iter().collect()
}

fn main() {
    let str1 = "listen";
    let str2 = "silent";

    if is_anagram(str1, str2) {
        println!("{} and {} are anagrams", str1, str2);
    } else {
        println!("{} and {} are not anagrams", str1, str2);
    }
}{codeBox}


Output


listen and silent are anagrams{codeBox}


Explanation


In this program, we define a function called is_anagram that takes two string references as input and returns a boolean indicating whether the strings are anagrams. The function first calls a helper function called sort_string on each string to obtain the sorted version of the string. It then compares the sorted versions of the two strings and returns true if they are equal, indicating that the strings are anagrams.

The sort_string function takes a string reference as input, converts it to a vector of characters, sorts the vector, and then converts it back into a string. This is necessary because Rust's built-in sort() method can only be used on mutable collections, so we first convert the string into a vector of characters to be able to sort it.

Finally, in the main() function, we define two strings str1 and str2 and call the is_anagram function on them. We then print a message indicating whether the strings are anagrams or not.




Post a Comment