你如何逐个字符地迭代

编程入门 行业动态 更新时间:2024-10-27 07:16:35
本文介绍了你如何逐个字符地迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

你如何逐个字符地迭代

本文发布于:2023-11-23 03:49:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!