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 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();
I wrote a function that returns the head of a &str
and the rest:
fn car_cdr(s: &str) -> (&str, &str) {
for i in 1..5 {
let r = s.get(0..i);
match r {
Some(x) => return (x, &s[i..]),
None => (),
}
}
(&s[0..0], s)
}
Use it like this:
let (first_char, remainder) = car_cdr("test");
println!("first char: {}\nremainder: {}", first_char, remainder);
The output looks like:
first char: t
remainder: est
It works fine with chars that are more than 1 byte.
The accepted answer is a bit ugly!
let text = "hello world!";
let ch = &text[0..1]; // this returns "h"