Rust Function: Check character case
Write a Rust function that takes a string slice and returns "Uppercase characters!" if all characters are uppercase, "Lowercase characters!" if all characters are lowercase, and "Mixedcase characters!" otherwise.
Sample Solution:
Rust Code:
// Function to determine the case of characters in a string slice.
fn check_case(s: &str) -> &'static str {
// Check if the string is empty
if s.is_empty() {
// If empty, return "Empty string!"
return "Empty string!";
}
// Check if all characters are uppercase
let is_uppercase = s.chars().all(|c| c.is_uppercase());
// Check if all characters are lowercase
let is_lowercase = s.chars().all(|c| c.is_lowercase());
// If all characters are uppercase, return "Uppercase characters!"
if is_uppercase {
"Uppercase characters!"
// If all characters are lowercase, return "Lowercase characters!"
} else if is_lowercase {
"Lowercase characters!"
// Otherwise, return "Mixedcase characters!"
} else {
"Mixedcase characters!"
}
}
fn main() {
// Example usage
let uppercase_str = "RUST";
let lowercase_str = "exercises";
let mixedcase_str = "HeLlO";
println!("{}", check_case(uppercase_str)); // Output: Uppercase characters!
println!("{}", check_case(lowercase_str)); // Output: Lowercase characters!
println!("{}", check_case(mixedcase_str)); // Output: Mixedcase characters!
}
Output:
Uppercase characters! Lowercase characters! Mixedcase characters!
Explanation:
The above code defines a function "check_case()" that takes a string slice 's' as input and determines the case of characters in the string.
- The function first checks if the input string is empty. If it is, it returns "Empty string!".
- It then checks if all characters in the string are uppercase using the "all()" method on the iterator returned by "chars()". If all characters are uppercase, it returns "Uppercase characters!".
- Next, it checks if all characters in the string are lowercase using a similar approach. If all characters are lowercase, it returns "Lowercase characters!".
- If neither of the above conditions is met, it concludes that the string contains a mix of uppercase and lowercase characters, and it returns "Mixedcase characters!".
In the "main()" function, example strings of different cases are created and passed to the "check_case()" function. The result of each call to "check_case()" is printed.
Rust Code Editor:
Previous: Rust Function: Check order of integers.
Next: Rust Function: Process result handling.
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