Home
Rust
String Uppercase First Letter
Updated Apr 4, 2023
Dot Net Perls
Uppercase first. Suppose we have a string in our Rust program and want it to have an uppercase first letter. We can transform "bird" into "Bird."
With some logic, we can copy the strings and uppercase certain letters in them. The chars() iterator is useful for looping over the initial string.
Loop, String Chars
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.
Note In uppercase_first, we call to_ascii_uppercase() on the first char in the string. Other chars are left unchanged.
Note 2 In uppercase_words, we call to_ascii_uppercase() on the first char in the string. Any chars after a space are also considered first chars.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 4, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen