Split a string keeping the separators

前端 未结 3 1594
既然无缘
既然无缘 2020-12-06 17:40

Is there a trivial way to split a string keeping the separators? Instead of this:

let texte = \"Ten. Million. Questions. Let\'s celebrate all we\'ve done tog         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 18:06

    Using str::match_indices:

    let text = "Ten. Million. Questions. Let's celebrate all we've done together.";
    
    let mut result = Vec::new();
    let mut last = 0;
    for (index, matched) in text.match_indices(|c: char| !(c.is_alphanumeric() || c == '\'')) {
        if last != index {
            result.push(&text[last..index]);
        }
        result.push(matched);
        last = index + matched.len();
    }
    if last < text.len() {
        result.push(&text[last..]);
    }
    
    println!("{:?}", result);
    

    Prints:

    ["Ten", ".", " ", "Million", ".", " ", "Questions", ".", " ", "Let\'s", " ", "celebrate", " ", "all", " ", "we\'ve", " ", "done", " ", "together", "."]
    

提交回复
热议问题