Example program. To begin we introduce 2 functions, uppercase_first and uppercase_words. These functions receive a str reference, and then return a new String.
Uppercase first We call to_ascii_uppercase() on the first char in the string. Other chars are left unchanged.
Uppercase words We call to_ascii_uppercase() on the first char in the string, and any chars after a space are considered first chars as well.
fn uppercase_first(data: &str) -> String {
// Uppercase first letter.
let mut result = String::new();
let mut first = true;
for value in data.chars() {
if first {
result.push(value.to_ascii_uppercase());
first = false;
} else {
result.push(value);
}
}
result
}
fn uppercase_words(data: &str) -> String {
// Uppercase first letter in string, and letters after spaces.
let mut result = String::new();
let mut first = true;
for value in data.chars() {
if first {
result.push(value.to_ascii_uppercase());
first = false;
} else {
result.push(value);
if value == ' ' {
first = true;
}
}
}
result
}
fn main() {
let test = "bird frog";
println!("UPPERCASE FIRST: {}", uppercase_first(test));
println!("UPPERCASE_WORDS: {}", uppercase_words(test));
}UPPERCASE FIRST: Bird frog
UPPERCASE_WORDS: Bird Frog
A summary. Many functions in Rust, like those used for implementing the uppercasing of first letters, are about the same as in other languages. Str reference arguments are important to understand.