CodeBlanks Logo Icon CodeBlanks

Summary - Strings

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

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
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 = &amp;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

Question
let girdi = "  42 \n";
let temiz = girdi.____();  // "42"
Answer
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

All lessons in Beginner