在Rust中,将& str拆分为每个字符一个& str的迭代器的惯用方式是什么? [英] In Rust, what's the idiomatic way to split a &str into an iterator of &strs of one character each?

查看:391
本文介绍了在Rust中,将& str拆分为每个字符一个& str的迭代器的惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想像"aeiou"这样使用&str并将其转换为大致等同于["a", "e", "i", "o", "u"].iter()的迭代器,最惯用的方法是什么?

If I want to take a &str like "aeiou" and turn it into an iterator roughly equivalent to ["a", "e", "i", "o", "u"].iter(), what's the most idiomatic way to do it?

我尝试做"aeiou".split(""),这对我来说似乎很惯用,但是我在开始和结束时都得到了空的&str.

I've tried doing "aeiou".split("") which seemed idiomatic to me, but I got empty &strs at the beginning and end.

我尝试做"aeiou".chars(),但是从那里尝试将char变成&str变得很丑陋和笨拙.

I've tried doing "aeiou".chars() but it got pretty ugly and unwieldy from there trying to turn the chars into &strs.

暂时,我只键入了["a", "e", "i", "o", "u"].iter(),但是必须有一种更简单,更惯用的方式.

For the time being, I just typed out ["a", "e", "i", "o", "u"].iter(), but there's got to be an easier, more idiomatic way.

对于上下文,我最终将遍历每个值,并将其传递给类似string.matches(vowel).count()的内容.

For context, I'm eventually going to be looping over each value and passing it into something like string.matches(vowel).count().

这是我的总体代码.也许我误入了其他地方.

Here's my overall code. Maybe I went astray somewhere else.

fn string_list_item_count<'a, I>(string: &str, list: I) -> usize
where
    I: IntoIterator<Item = &'a str>,
{
    let mut num_instances = 0;

    for item in list {
        num_instances += string.matches(item).count();
    }

    num_instances
}

// snip

string_list_item_count(string, vec!["a", "e", "i", "o", "u"])

// snip

如果我可以让string_list_item_count接受迭代器中的std::str::pattern::Pattern特性,我认为这会使该函数接受&strchar的迭代器,但是Pattern特性是一个夜间不稳定的API,我正试图避免使用那些.

If I could make string_list_item_count accept the std::str::pattern::Pattern trait inside the iterator, I think that would make this function accept iterators of &str and char, but the Pattern trait is a nightly unstable API and I'm trying to avoid using those.

推荐答案

您可以使用 split_terminator 而不是split,以跳过迭代器末尾的空字符串.此外,如果您 skip 迭代器的第一个元素,您将得到想要的结果:

You can use split_terminator instead of split to skip the empty string at the end of the iterator. Additionally, if you skip the first element of the iterator, you get the result you want:

let iterator = "aeiou".split_terminator("").skip(1);
println!("{:?}", iterator.collect::<Vec<_>>());

输出:

["a", "e", "i", "o", "u"]

这篇关于在Rust中,将&amp; str拆分为每个字符一个&amp; str的迭代器的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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