UTF-8 does not define what "character" is so it depends on what you want. In this case, char
s 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…