簡體   English   中英

在 Rust 中,將 &str 拆分為每個包含一個字符的 &strs 迭代器的慣用方法是什么?

[英]In Rust, what's the idiomatic way to split a &str into an iterator of &strs of one character each?

如果我想把&str"aeiou"變成一個迭代器,大致相當於["a", "e", "i", "o", "u"].iter() ,什么是最慣用的怎么做?

我試過做"aeiou".split("")這對我來說似乎是慣用的,但我在開始和結束時都得到了空&str s。

我試過做"aeiou".chars()但它變得非常丑陋和笨拙,試圖將char s 轉換為&str s。

目前,我只是輸入["a", "e", "i", "o", "u"].iter() ,但必須有一種更簡單、更慣用的方式。

對於上下文,我最終將遍歷每個值並將其傳遞到string.matches(vowel).count()類的東西中。

這是我的整體代碼。 也許我在別的地方誤入歧途了。

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,我正在嘗試避免使用那些。

您可以使用split_terminator而不是split來跳過迭代器末尾的空字符串。 此外,如果你skip迭代器的第一個元素,你會得到你想要的結果:

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

輸出:

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

閉包也可以作為Pattern

fn main() {
    let vowels = "aeiou";
    let s = "the quick brown fox jumps over the lazy dog";
    let count = string_item_count(s, vowels);
    dbg!(count);
}

fn string_item_count(string: &str, pat: &str) -> usize {
    let pred = |c| pat.contains(c);
    string.matches(pred).count()
}

我將str::split與空字符串一起使用,然后使用Iterator::filter刪除任何空字符串:

fn string_chars(s: &str) -> impl Iterator<Item = &str> {
    s.split("").filter(|s| !s.is_empty())
}

fn main() {
    assert_eq!(
        string_chars("aeiou").collect::<Vec<_>>(),
        ["a", "e", "i", "o", "u"],
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM