小编rus*_*ari的帖子

在 Rust 中枚举字符串的最佳方法是什么?(chars() 与 as_bytes())

我是 Rust 新手,我正在使用 Rust Book 来学习它。

最近,我在那里发现了这个功能:

// Returns the number of characters in the first
// word of the given string

fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}
Run Code Online (Sandbox Code Playgroud)

如您所见,作者在这里使用 String::as_bytes() 方法来枚举字符串。然后,他们将 char ' ' 转换为 u8 类型,以检查我们是否已到达第一个单词的末尾。

据我所知,还有另一种选择,看起来更好:

fn first_word(s: &String) -> usize {
    for (i, item) in s.chars().enumerate() {
        if item == ' ' {
            return i; …
Run Code Online (Sandbox Code Playgroud)

rust

6
推荐指数
1
解决办法
1013
查看次数

标签 统计

rust ×1