CodeBlanks Logo Icon CodeBlanks

Slicing strings

Learn the correct way to slice a substring.

Slicing strings

Slicing text with a byte range panics if the range falls in the middle of a character. That's why Rust doesn't allow single-index access like s[0] at all:

let s = "Çiçekçi";
// let c = s[0];        // error: str can't be indexed
// let x = &s[0..1];    // panic: Ç is two bytes
println!("{}", s.is_char_boundary(2));   // true
println!("{}", &s[0..2]);                // Ç

char_indices

If you want to slice at a character boundary without copying, char_indices gives the byte position of each character:

let s = "Çiçekçi";
for (i, c) in s.char_indices().take(4) {
    print!("{i}:{c} ");     // 0:Ç 2:i 3:ç 5:e
}
let (son, _) = s.char_indices().nth(3).unwrap();
println!("{}", &s[..son]);   // Çiç

The byte where the 4th character starts (5) is where the first three characters end.

Practice Safe first three

For let s = "Çiçekçi";, find the byte position of the 4th character with char_indices().nth(3). Print the slice &s[..konum] and the position separated by a space.

Starter code

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

Sample solution

main.rs
fn main() {
    let s = "Çiçekçi";
    let (konum, _) = s.char_indices().nth(3).unwrap();
    println!("{} {}", &s[..konum], konum);
}

Expected output

Çiç 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the simplest way to safely take the first 3 characters of a text?

  • s[3]
  • s.bytes().take(3)
  • s.chars().take(3).collect::<String>() Correct answer
  • &s[0..3]

Explanation: chars advances by character boundaries; &s[0..3] may panic with Turkish letters.

2 Byte positions

Question
for (i, c) in s.____() {
    println!("{i}: {c}");
}
Answer
for (i, c) in s.char_indices() {
    println!("{i}: {c}");
}

Explanation: char_indices yields (byte position, character) pairs.

3 Expression and result on "Çiçekçi"

Term Meaning
&s[0..2] "Ç"
&s[0..1] Panic
s.is_char_boundary(1) false
s.char_indices().nth(3) Some((5, 'e'))

All lessons in Beginner