在 Rust 中获取字符串中第 n 个字符的值

Get value of nth char in string in rust

如何获取字符串中 n 位置的字符值? 例如,如果我有字符串“Hello, world!”,我如何获取第一个字符的值?

就像s.chars().nth(n)一样简单。

但是,请注意 the docs 中所说的:

It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead.

参见

具体第一个字符,可以使用s.chars().next().

如果你的字符串是ASCII-only,你可以使用as_bytes()s.as_bytes()[n]。但我不建议这样做,因为这不是 future-proof(虽然这更快,O(1) vs O(n))。