string 你如何逐个字符地遍历一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22118221/
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-09 02:14:00  来源:igfitidea点击:

How do you iterate over a string by character

stringiteratorrust

提问by user2171584

I have a string and I need to scan for every occurrence of "foo" and read all the text following it until a second ". Since Rust does not have a containsfunction for strings, I need to iterate by characters scanning for it. How would I do this?

我有一个字符串,我需要扫描每次出现的“foo”并阅读它后面的所有文本,直到一秒钟"由于 Rust 没有contains用于 strings的函数,我需要通过字符扫描来迭代它。我该怎么做?

Edit: Rust's &strhas a contains()and find()method.

编辑:Rust&str有一个contains()andfind()方法。

回答by centaurian_slug

I need to iterate by characters scanning for it.

我需要通过字符扫描来迭代它。

The .chars()methodreturns an iterator over characters in a string. e.g.

.chars()方法返回字符串中字符的迭代器。例如

for c in my_str.chars() { 
    // do something with `c`
}

for (i, c) in my_str.chars().enumerate() {
    // do something with character `c` and index `i`
}

If you are interested in the byte offsets of each char, you can use char_indices.

如果您对每个字符的字节偏移量感兴趣,可以使用char_indices.

Look into .peekable(), and use peek()for looking ahead. It's wrapped like this because it supports UTF-8 codepoints instead of being a simple vector of characters.

Look into .peekable()peek()用于展望未来。它是这样包装的,因为它支持 UTF-8 代码点,而不是一个简单的字符向量。

You could also create a vector of chars and work on it from there, but that's more time and space intensive:

您也可以创建一个chars向量并从那里开始处理它,但这需要更多的时间和空间:

let my_chars: Vec<_> = mystr.chars().collect();