chars and bytes
- Rust course
- Beginner
- Lesson 101/115
- 4 min
Split a string into chars or bytes iterators.
chars and bytes
Rust stores text as UTF-8. Turkish letters (ç, ğ, ı, ö, ş, ü) take two bytes. That's why len() gives the byte count and chars().count() the character count:
let s = "çay";
println!("{} {}", s.len(), s.chars().count()); // 4 3
for b in s.bytes() { print!("{b} "); } // 195 167 97 121Use chars() to process text character by character; the byte level is only for binary protocols and ASCII work.
The char type
char is a 4-byte Unicode scalar value, written in single quotes. It has handy methods:
let c = 'ğ';
println!("{}", c.is_alphabetic()); // true
println!("{}", '7'.to_digit(10).unwrap()); // 7
println!("{}", 'a'.to_ascii_uppercase()); // A
let ters: String = "abc".chars().rev().collect(); // "cba"to_uppercase() returns an iterator, not a single char, because the uppercase form of some letters is more than one character (ß → SS).
Practice Letters and bytes
For let s = "Ağaç";, print the byte count, the character count and the characters reversed (chars().rev().collect::<String>()) on one line.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let s = "Ağaç";
let ters: String = s.chars().rev().collect();
println!("{} {} {}", s.len(), s.chars().count(), ters);
}Expected output
6 4 çağA
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>"şeker".len()</code>?
- 5
- 10
- 4
- 6 Correct answer
Explanation: "ş" is two bytes, the remaining four letters one byte each: 2 + 4 = 6.
2 Count characters
let s = "çay";
let n = s.____().count(); // 3
let s = "çay";
let n = s.chars().count(); // 3
Explanation: chars yields the Unicode characters one by one.
3 Expression and result
| Term | Meaning |
|---|---|
"çay".len() |
4 |
"çay".chars().count() |
3 |
'ğ'.is_alphabetic() |
true |
"abc".chars().rev() |
"cba" (with collect) |