Summary - Strings
- Rust course
- Beginner
- Lesson 24/115
- 5 min
Combine String and &str to build a greeting message.
Strings summary
&str is borrowed and immutable; String is owned and growable. Creating: String::from, to_string, String::with_capacity. Appending: push_str, push, +=, + (takes ownership of the left side). Formatting: format!. Length: len counts bytes, chars().count() characters.
Case and whitespace
Common methods return a new value; they don't change the original text:
let s = " Merhaba Rust ";
println!("[{}]", s.trim()); // [Merhaba Rust]
println!("{}", s.to_uppercase()); // MERHABA RUST
println!("{}", s.contains("Rust")); // true
println!("{}", s.replace("Rust", "Go"));to_uppercase applies Unicode rules: "ş".to_uppercase() → "Ş".
Practice Clean and capitalize
Write fn temizle(s: &str) -> String: remove leading/trailing whitespace with trim and capitalize with to_uppercase. Print the result of temizle(" şeker ") and its length (len).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn temizle(s: &str) -> String {
s.trim().to_uppercase()
}
fn main() {
let t = temizle(" şeker ");
println!("{} {}", t, t.len());
}Expected output
ŞEKER 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 With <code>let s = String::from("Rust"); let k = &s[0..1];</code>, what is k?
- A compile error
- "R" (&str) Correct answer
- 'R' (char)
- 82
Explanation: Slicing with a byte range gives a &str; if the range falls in the middle of a character, it panics at run time.
2 Trim whitespace
let girdi = " 42 \n";
let temiz = girdi.____(); // "42"
let girdi = " 42 \n";
let temiz = girdi.trim(); // "42"
Explanation: trim removes leading and trailing whitespace and newlines.
3 Group summary
| Term | Meaning |
|---|---|
&str |
Borrowed view |
String |
Owned text |
format! |
Formatted String |
chars().count() |
Character count |