CodeBlanks Logo Icon CodeBlanks

String length

Inspect a string with len, is_empty and chars methods.

String length

len() gives the number of bytes, not characters. Turkish letters are 2 bytes in UTF-8; for the character count use chars().count():

let s = "çay";
println!("{}", s.len());            // 4
println!("{}", s.chars().count());  // 3
println!("{}", "".is_empty());      // true

That's why Rust doesn't allow integer indexing like s[0]: a byte could be in the middle of a character.

chars and bytes

chars() splits the text into Unicode characters, bytes() into raw bytes. To get the n-th character use chars().nth(n); it returns an Option<char> because the text might be short:

let s = "Gölge";
println!("{:?}", s.chars().nth(1));   // Some('ö')
println!("{:?}", s.bytes().nth(1));   // Some(195) – ö's first byte
println!("{:?}", s.chars().nth(9));   // None

Practice Bytes and characters

For let s = "Gölge";, print s.len(), s.chars().count() and s.chars().nth(1) with println!("{} {} {:?}", ...).

Starter code

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

Sample solution

main.rs
fn main() {
    let s = "Gölge";
    println!("{} {} {:?}", s.len(), s.chars().count(), s.chars().nth(1));
}

Expected output

6 5 Some('ö')

Questions and answers

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

1 What is <code>"ğğ".len()</code>?

  • 1
  • 8
  • 4 Correct answer
  • 2

Explanation: ğ is 2 bytes in UTF-8; two of them make 4 bytes. The character count with chars().count() is 2.

2 Count characters

Question
let n = "ışık".chars().____();  // 4
Answer
let n = "ışık".chars().count();  // 4

Explanation: chars().count() gives the character count; len counts bytes.

3 Expression and result ("çay")

Term Meaning
len() 4
chars().count() 3
chars().nth(0) Some('ç')
is_empty() false

All lessons in Beginner