Summary - Advanced strings
- Rust course
- Beginner
- Lesson 105/115
- 5 min
Combine split, contains and replace to build a text filter.
Advanced strings summary
String is owned and &str borrowed text; take &str in parameters. Text is UTF-8: len() counts bytes, chars().count() counts characters; byte slices must be on character boundaries. Searching: contains, find, starts_with; replacing: replace; splitting: split, split_whitespace, lines, split_once; joining: join, format!, push_str.
Capitalizing the first letter
To capitalize the first letter of a word, the first character is split off, uppercased and joined with the remaining slice:
fn ilk_buyuk(k: &str) -> String {
let mut c = k.chars();
match c.next() {
Some(ilk) => ilk.to_uppercase().collect::<String>() + c.as_str(),
None => String::new(),
}
}c.as_str() gives the not-yet-read part of the iterator as a slice.
Practice Capitalize words
Write the ilk_buyuk function above. Split the text "rust çok hızlı" with split_whitespace, apply it to each word, join with join(" ") and print.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn ilk_buyuk(k: &str) -> String {
let mut c = k.chars();
match c.next() {
Some(ilk) => ilk.to_uppercase().collect::<String>() + c.as_str(),
None => String::new(),
}
}
fn main() {
let s = "rust çok hızlı";
let parcalar: Vec<String> = s.split_whitespace().map(ilk_buyuk).collect();
println!("{}", parcalar.join(" "));
}Expected output
Rust Çok Hızlı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the result of <code>"istanbul".to_uppercase()</code>?
- "İSTANBUL"
- "Istanbul" Correct answer
- Compile error
- "ISTANBUL" (not the Turkish İ)
Explanation: The standard library isn't locale-aware; it converts i → I. Turkish rules need a separate library or a manual mapping.
2 Split into words
let kelimeler: Vec<&str> = s.____().collect();
let kelimeler: Vec<&str> = s.split_whitespace().collect();
Explanation: split_whitespace separates words regardless of the number of spaces.
3 Group summary
| Term | Meaning |
|---|---|
s.len() |
Byte count |
s.chars() |
Characters |
s.split(..) |
Pieces |
v.join(..) |
Joining |