Rust Function: Find smallest string
Write a Rust function that takes two string references and returns the smallest one.
Sample Solution:
Rust Code:
// Define a function named 'find_smallest' that takes two string references 'str1' and 'str2'
fn find_smallest<'a>(str1: &'a str, str2: &'a str) -> &'a str {
// Check if 'str1' is less than 'str2' lexicographically
// If it is, return 'str1', otherwise return 'str2'
if str1 < str2 {
str1
} else {
str2
}
}
fn main() {
// Define two string variables
let string1 = "abc";
let string2 = "abcd";
// Call the 'find_smallest' function and pass the string references
let smallest = find_smallest(&string1, &string2);
// Print the smallest string
println!("The smallest string is: {}", smallest);
}
Output:
The smallest string is: abc
Explanation:
Here's a brief explanation of the above Rust code:
- fn find_smallest<'a>(str1: &'a str, str2: &'a str) -> &'a str { ... }: This line defines a function named "find_smallest()" that takes two string references 'str1' and 'str2' as input parameters and returns a string reference. The lifetime 'a ensures that the returned reference lives at least as long as the input reference.
- if str1 < str2 { ... } else { ... }: This line checks if 'str1' is lexicographically less than 'str2'. If it is, 'str1' is returned; otherwise, 'str2' is returned. This comparison is based on lexicographical ordering, where shorter strings are considered smaller, and if two strings have the same prefix, the one with the smaller suffix is considered smaller.
- let smallest = find_smallest(&string1, &string2);: This line calls the "find_smallest()" function and passes references to the two string variables 'string1' and 'string2'.
- println!("The smallest string is: {}", smallest);: This line prints the smallest string returned by the "find_smallest()" function.
Rust Code Editor:
Previous: Rust Function: Modify variable reference.
Next: Rust Program: Define Person Struct.
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