Getting a single character out of a string

2019-01-27 12:17发布

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.

标签: string rust
3条回答
Viruses.
2楼-- · 2019-01-27 13:08

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();
查看更多
贼婆χ
3楼-- · 2019-01-27 13:13

The accepted answer is a bit ugly!

let text = "hello world!";

let ch = &text[0..1]; // this returns "h"
查看更多
等我变得足够好
4楼-- · 2019-01-27 13:19

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.

查看更多
登录 后发表回答