简体   繁体   English

获取 rust 中字符串中第 n 个字符的值

[英]Get value of nth char in string in rust

How do I get the value of a character at position n in a string?如何获取字符串中 position n处字符的值? For example, if I had the string "Hello, world,"?例如,如果我有字符串“Hello, world,”? how would I get the value of the first character?我将如何获得第一个字符的值?

It's simple as s.chars().nth(n) .就像s.chars().nth(n)一样简单。

However, beware that like said in 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.请务必记住, char表示 Unicode 标量值,可能与您对“字符”的理解不符。 Iteration over grapheme clusters may be what you actually want.迭代字素簇可能是您真正想要的。 This functionality is not provided by Rust's standard library, check crates.io instead. Rust 的标准库不提供此功能,请改为检查 crates.io。

See How to iterate over Unicode grapheme clusters in Rust?请参阅如何迭代 Rust 中的 Unicode 个字素簇? . .

For the first character specifically, you can use s.chars().next() .具体对于第一个字符,您可以使用s.chars().next()

If your string is ASCII-only, you can use as_bytes() : s.as_bytes()[n] .如果您的字符串仅包含 ASCII,则可以使用as_bytes()s.as_bytes()[n] But I would not recommend that, as this is not future-proof (though this is faster, O(1) vs O(n)).但我不建议这样做,因为这不是面向未来的(尽管这更快,O(1) vs O(n))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM