Rust Function: Reverse a string
Write a Rust function that takes a string and returns the reverse of the string.
Sample Solution:
Rust Code:
// Define a function named 'reverse_string' that takes a string as input and returns its reverse
fn reverse_string(input: &str) -> String {
// Create a new String to store the reversed string
let mut reversed_string = String::new();
// Iterate over the characters of the input string in reverse order
for c in input.chars().rev() {
reversed_string.push(c); // Append each character to the reversed string
}
reversed_string // Return the reversed string
}
fn main() {
let input_string = "hello"; // Define the input string
// Call the 'reverse_string' function with the input string and store the result
let reversed = reverse_string(input_string);
// Print the reversed string
println!("Original string: {}", input_string);
println!("Reversed string: {}", reversed);
}
Output:
Original string: hello Reversed string: olleh
Explanation:
Here's a brief explanation of the above Rust code:
- 'fn reverse_string(input: &str) -> String { ... }': This is a function named 'reverse_string' that takes a string slice ('&str') as input and returns a new 'String' containing the reverse of the input string.
- Inside the function:
- Create a new 'String' named 'reversed_string' to store the reversed string.
- Iterate over the characters of the input string in reverse order using '.chars().rev()'.
- For each character 'c', we append it to the 'reversed_string' using '.push(c)'.
- Finally, we return the 'reversed_string' as the result of the function.
- In the 'main' function, we define an input string.
- We call the 'reverse_string' function with the input string and store the result in a variable named 'reversed'.
- We then print both the original and reversed strings.
Rust Code Editor:
Previous: Rust Function: Calculate factorial of a number.
Next: Rust Program: Calculate nth Fibonacci number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics