I want to get the first character of a std::str
. The method char_at()
is currently unstable, as is slice_chars
in std::string::String
.
The only option I have currently come up with is the following.
let text = "hello world!";
let char_vec:Vec<char> = text.chars().collect();
let ch = char_vec[0];
But this seems excessive to just get a single character, and not use the rest of the vector.
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 firstchar
of a&str
is going to be between one and four bytes.If you want just the first
char
, then don't collect into aVec<char>
, just use the iterator:The accepted answer is a bit ugly!
I wrote a function that returns the head of a
&str
and the rest:Use it like this:
The output looks like:
It works fine with chars that are more than 1 byte.