string 从字符串中取出单个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30811107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:23:35  来源:igfitidea点击:

Getting a single character out of a string

stringrust

提问by XAMPPRocky

I want to get the first character of a std::str. The method char_at()is currently unstable, as is slice_charsin std::string::String.

我想获得 a 的第一个字符std::str。该方法char_at()目前不稳定,就像slice_charsstd::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.

但这似乎过分了,只得到一个字符,而不使用向量的其余部分。

回答by Steve Klabnik

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 charof a &stris going to be between one and four bytes.

UTF-8 没有定义“字符”是什么,所以它取决于你想要什么。在这种情况下,chars 是 Unicode 标量值,因此 a 的第char一个&str将介于 1 到 4 个字节之间。

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

如果您只想要第一个char,则不要收集到 a 中Vec<char>,只需使用迭代器:

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

回答by Sean

I wrote a function that returns the head of a &strand the rest:

我写了一个函数,返回 a 的头部&str和其余部分:

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.

它适用于超过 1 个字节的字符。

回答by FeFiFoFu

The accepted answer is a bit ugly!

接受的答案有点难看!

let text = "hello world!";

let ch = &text[0..1]; // this returns "h"