How do I get the first character out of a string?

UTF-8 does not define what “character” is so it depends on what you want. In this case, chars are Unicode scalar values, and so the first char of a &str is going to be between one and four bytes.

If you want just the first char, then don’t collect into a Vec<char>, just use the iterator:

let text = "hello world!";
let ch = text.chars().next().unwrap();

Alternatively, you can use the iterator’s nth method:

let ch = text.chars().nth(0).unwrap();

Bear in mind that elements preceding the index passed to nth will be consumed from the iterator.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)