String length
- Rust course
- Beginner
- Lesson 23/115
- 4 min
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()); // trueThat'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)); // NonePractice Bytes and characters
For let s = "Gölge";, print s.len(), s.chars().count() and s.chars().nth(1) with println!("{} {} {:?}", ...).
Starter code
fn main() {
// buraya yaz
}Sample solution
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
let n = "ışık".chars().____(); // 4
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 |