你如何逐个字符地迭代 [英] How do you iterate over a string by character

查看:146
本文介绍了你如何逐个字符地迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我需要扫描每次出现的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 <的向量/ code> 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();

这篇关于你如何逐个字符地迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆