Skip to content
Justice Tech School

String Slicing and Chars

Slice with byte ranges like &s[0..5], which panics inside a character. chars() iterates characters, and char_indices gives positions.

Example
let s = "héllo";
println!("{} {}", s.len(), s.chars().count());
println!("{}", &s[0..1]);
for (i, c) in "ab".char_indices() { print!("{}:{} ", i, c); }
println!();

Result

6 5
h
0:a 1:b 

Exercise

Count characters.

s.chars().()

Quiz Test

Does len() count characters?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.