我有一个字符串,我需要扫描每次出现的foo并读取其后的所有文本,直到第二个。自Rust执行以来没有包含字符串的函数,我需要通过字符扫描来迭代它。我该怎么做?
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 contains function for strings, I need to iterate by characters scanning for it. How would I do this?
编辑:Rust的& str 有一个 包含() 和 find() method。
Edit: Rust's &str has a contains() and find() method.
推荐答案
我需要通过字符扫描来迭代它。
I need to iterate by characters scanning for it.
。 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_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 s并从那里开始工作,但这需要更多的时间和空间:
You could also create a vector of chars and work on it from there, but that's more time and space intensive:
let my_chars: Vec<_> = mystr.chars().collect();更多推荐
你如何逐个字符地迭代
发布评论