Check If A String Is A Palindrome In Rust
Code snippet for how to Check If A String Is A Palindrome In Rust with sample and detail explanation
In this article, we’ll decipher how you can check if a string is a palindrome or not using Rust. Palindromes are strings that remain identical even if they are reversed, offering some interesting problems to address in any programming language.
Code Snippet to Check If A String Is A Palindrome
Below is the code snippet that can be used in Rust to verify if a string is a palindrome or not:
// Check if string is a palindrome in Rust
fn is_palindrome(s: &str) -> bool {
let s = s.chars().collect::<Vec<char>>();
s == s.iter().rev().cloned().collect::<Vec<char>>()
}
fn main() {
println!("{}", is_palindrome("radar")); // Output: true
}
Code Explanation for Checking if a String is a Palindrome
Let’s breakdown the provided snippet to understand how Rust checks if a string is a palindrome or not.
First, we are defining a function is_palindrome
that takes a string slice reference (&str
) as an argument, and returns a boolean value that indicates whether the string is a palindrome or not.
fn is_palindrome(s: &str) -> bool { ... }
Within the function itself, we first convert the string slice into a Vector of characters. In Rust, a String
cannot directly be reversed, as it is a vector of bytes, not characters. Therefore, for string manipulations such as reversing, we first need to convert it into a vector of characters.
let s = s.chars().collect::<Vec<char>>();
Finally, we check if the vector is equal to its reversed version. iter().rev()
generates an iterator that moves from the end to the start of the vector. cloned()
is used to copy the elements, and collect::<Vec<char>>()
converts the iterator back into a vector. The equality operator ==
compares the vectors element by element.
s == s.iter().rev().cloned().collect::<Vec<char>>()
If both vectors are identical, the function will return true
, indicating that the string is indeed a palindrome. Otherwise, it will return false
.
The main function might look like this:
fn main() {
println!("{}", is_palindrome("radar")); // Output: true
}
The string “radar” is passed to the is_palindrome
function and the result is printed, which in this case will be true
, as “radar” is a palindrome.
There you have it. Now you can easily verify if a string is a palindrome or not in Rust.