Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

rust - Split a string keeping the separators

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 together.";
let v: Vec<&str> = texte.split(|c: char| !(c.is_alphanumeric() || c == ''')).filter(|s| !s.is_empty()).collect();

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

I would like something that gives me :

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

I am trying that kind of code (it assumes the string begins with a letter and ends with a 'non'-letter) :

let texte = "Ten. Million. Questions. Let's celebrate all we've done together.  ";
let v1: Vec<&str> = texte.split(|c: char| !(c.is_alphanumeric() || c == ''')).filter(|s| !s.is_empty()).collect();
let v2: Vec<&str> = texte.split(|c: char| c.is_alphanumeric() || c == ''').filter(|s| !s.is_empty()).collect();
let mut w: Vec<&str> = Vec::new();

let mut j = 0;
for i in v2 {
    w.push(v1[j]);
    w.push(i);
    j = j+1;
}

It gives me almost the result I wrote earlier but it's good :

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

However is there a better way to code that ? Because I tried to enumerate on v2 but it didn't work, and it looks rough to use j in the for loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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", "."]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...