问题描述
我有一个字符串,我需要扫描每次出现的foo"并读取它后面的所有文本,直到第二个 "
.,我需要通过字符扫描来迭代它.我该怎么做?
I have a string and I need to scan for every occurrence of "foo" and read all the text following it until a second "
. , I need to iterate by characters scanning for it. How would I do this?
编辑:Rust 的 &str
有一个 contains()
和 find()
方法.
Edit: Rust's &str
has a contains()
and find()
method.
推荐答案
.chars()
方法返回字符串中字符的迭代器.例如
The .chars()
method returns an iterator over characters in a string. e.g.
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`
}
如果你对每个char的字节偏移量感兴趣,可以使用char_indices
.
If you are interested in the byte offsets of each char, you can use char_indices
.
查看 .peekable()
,并使用 peek()
进行查看.之所以这样包装,是因为它支持 UTF-8 代码点,而不是简单的字符向量.
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.
您也可以创建一个 char
向量并从那里开始处理它,但这需要更多的时间和空间:
You could also create a vector of char
s and work on it from there, but that's more time and space intensive:
let my_chars: Vec<_> = mystr.chars().collect();
这篇关于你如何逐个字符地遍历一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!