计算重复字符的迭代器适配器

Анд*_*рей 1 string monads count char rust

我有一个像“aaaabbbccccc”这样的字符串。我想在字符串的chars迭代器上创建一个适配器,以生成相同字符的计数。输出(count)需要是连续相同字符的数量。例如:

let s = "aaaabbbccccc"
for count in s.chars().MAGIC() {
    println!("{}", count)
}
// prints: 4, 3, 5
Run Code Online (Sandbox Code Playgroud)

更新:这几乎有效:过去不考虑字母:

let s = "aaaabbbcccccdd".to_string();
let mut tt = (s.chars().nth(0).unwrap(), 0);
for a in s.chars().filter_map(|x| {
    if x != tt.0 {
        tt.0 = x;
        let tt_temp = tt.1;
        tt.1 = 1;
        Some(tt_temp)
    } else {
        tt.1 += 1;
        None
    }
}) {
    println!("{:?}", a);
}
Run Code Online (Sandbox Code Playgroud)

blu*_*uss 7

使用itertools' .coalesce()你可以这样做:

// Map each char to an initial count of 1, then merge counts for identical chars
.map(|c| (c, 1)).coalesce(|(c, n), (d, m)|
    if c == d { Ok((c, n + m)) } else { Err(((c, n), (d, m))) })
Run Code Online (Sandbox Code Playgroud)