fn is_palindrome(string: &str) -> bool {
// Initialize a boolean variable to track if the string is a palindrome.
let mut is_palindrome = true;
// Iterate over the string backwards.
for i in (1..string.len()).rev() {
// Check if the current character is not equal to the character at the same index from the beginning of the string.
if string[i] != string[string.len() - i - 1] {
// The string is not a palindrome.
is_palindrome = false;
break;
}
}
// Return the boolean variable.
return is_palindrome;
}
fn main() {
// Get the string from the user.
let mut string = String::new();
io::stdin().read_line(&mut string).unwrap();
// Check if the string is a palindrome.
let is_palindrome = is_palindrome(&string);
// Print the result.
if is_palindrome {
println!("The string {} is a palindrome.", string);
} else {
println!("The string {} is not a palindrome.", string);
}
}
This program first initializes a boolean variable to track if the string is a palindrome. The program then iterates over the string backwards. For each character in the loop, the program checks if the character is not equal to the character at the same index from the beginning of the string. If the character is not equal, then the program sets the boolean variable to false and breaks out of the loop. Finally, the program returns the boolean variable.
To run this program, you can save it as a .rs file and then compile and run it using the following commands:
Code snippet
rustc is_palindrome.rs
./is_palindrome
This will prompt you to enter a string. Enter a string and press Enter. The program will then print whether the string is a palindrome or not.
For example, if you enter the string "racecar", the program will print the following output:
Code snippet
The string "racecar" is a palindrome.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust program to check if a given string is a palindrome:
Rust
This program first initializes a boolean variable to track if the string is a palindrome. The program then iterates over the string backwards. For each character in the loop, the program checks if the character is not equal to the character at the same index from the beginning of the string. If the character is not equal, then the program sets the boolean variable to false and breaks out of the loop. Finally, the program returns the boolean variable.
To run this program, you can save it as a
.rsfile and then compile and run it using the following commands:Code snippet
This will prompt you to enter a string. Enter a string and press Enter. The program will then print whether the string is a palindrome or not.
For example, if you enter the string "racecar", the program will print the following output:
Code snippet