如何从字符串中获取第一个字符? [英] How do I get the first character out of a string?
问题描述
我想获取 std::str 的第一个字符
.方法 char_at()
目前不稳定,String::slice_chars
.
我想出了以下内容,但获得单个字符而不使用向量的其余部分似乎有些过分:
I have come up with the following, but it seems excessive to get a single character and not use the rest of the vector:
let text = "hello world!";
let char_vec: Vec<char> = text.chars().collect();
let ch = char_vec[0];
推荐答案
UTF-8 没有定义什么字符"所以这取决于你想要什么.在这种情况下,char
s 是 Unicode 标量值,因此 &str
的第一个 char
将介于 1 和 4 之间字节.
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.
如果你只想要第一个 char
,那么不要收集到 Vec
,只需使用迭代器:
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();
或者,您可以使用迭代器的 第n个
方法:
Alternatively, you can use the iterator's nth
method:
let ch = text.chars().nth(0).unwrap();
请记住,传递给 nth
的索引之前的元素将从迭代器中消耗.
Bear in mind that elements preceding the index passed to nth
will be consumed from the iterator.
这篇关于如何从字符串中获取第一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!