pub fn ucwords(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut capitalize_next = true;
for ch in s.chars() {
if capitalize_next && ch.is_alphabetic() {
result.extend(ch.to_uppercase());
capitalize_next = false;
} else {
result.push(ch);
capitalize_next = ch.is_whitespace();
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capitalizes_the_first_letter_of_each_word() {
assert_eq!(ucwords("hello world"), "Hello World");
}
#[test]
fn leaves_the_rest_of_each_words_casing_untouched() {
assert_eq!(ucwords("hELLo wORLD"), "HELLo WORLD");
}
#[test]
fn handles_multiple_spaces_and_leading_whitespace() {
assert_eq!(ucwords(" hello world"), " Hello World");
}
#[test]
fn handles_an_empty_string() {
assert_eq!(ucwords(""), "");
}
#[test]
fn handles_a_single_word() {
assert_eq!(ucwords("rust"), "Rust");
}
}