Rust Function: Determine Palindrome
Rust Functions and Control Flow: Exercise-10 with Solution
Write a Rust function to check if a string is a palindrome.
Sample Solution:
Rust Code:
// Define a function named 'is_palindrome' that takes a string as input and returns true if it's a palindrome, false otherwise
fn is_palindrome(s: &str) -> bool {
// Convert the string to lowercase to ignore case sensitivity
let s_lower = s.to_lowercase();
// Check if the reversed string is equal to the original string
s_lower.chars().eq(s_lower.chars().rev())
}
fn main() {
let string1 = "madam"; // Define a palindrome string
let string2 = "hello"; // Define a non-palindrome string
// Check if string1 is a palindrome
if is_palindrome(string1) {
println!("'{}' is a palindrome.", string1);
} else {
println!("'{}' is not a palindrome.", string1);
}
// Check if string2 is a palindrome
if is_palindrome(string2) {
println!("'{}' is a palindrome.", string2);
} else {
println!("'{}' is not a palindrome.", string2);
}
}
Output:
'madam' is a palindrome. 'hello' is not a palindrome.
Explanation:
Here's a brief explanation of the above Rust code:
- fn is_palindrome(s: &str) -> bool { ... }: This is a function named "is_palindrome()" that takes a string slice 's' as input and returns a boolean ('bool'). It checks whether the given string is a palindrome.
- Inside the function:
- We convert the input string 's' to lowercase using the "to_lowercase()" method ignoring case sensitivity.
- We use the "eq()" method to compare the characters of the original string with the characters of its reverse (obtained by "rev()"). If they are equal, the function returns 'true', indicating that the string is a palindrome; otherwise, it returns 'false'.
- In the main function,
- Define two strings, 'string1' and 'string2'.
- Check if each string is a palindrome using the "is_palindrome()" function and print the result.
Rust Code Editor:
Previous: Rust Function: Find Sum of array elements.
Next: Rust Ownership, Borrowing, and Lifetimes Exercises
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/basic/rust-functions-and-control-flow-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics