是否有一種簡單的方法來拆分保留分隔符的字符串? 取而代之的是:拆分保持分隔符的字符串
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();
與["Ten", "Million", "Questions", "Let's", "celebrate", "all", "we've", "done", "together"]
結果。
我想的東西,給我:
["Ten", ".", " ", "Million", ".", " ", "Questions", ".", " ", "Let's", " ", "celebrate", " ", "all", " ", "we've", " ", "done", " ", "together", "."]
。
我想那樣的代碼(它假定字符串開頭一個字母和一個「non'字母結尾):
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;
}
這讓我幾乎我前面寫的結果,但它的好:
["Ten", ". ", "Million", ". ", "Questions", ". ", "Let's", " ", "celebrate", " ", "all", " ", "we've", " ", "done", " ", "together", "."]
但是有沒有更好的方法來編碼?因爲我試圖枚舉v2,但它不起作用,並且在for循環中使用j看起來很粗糙。
正則表達式是你所需要的。 – Onilol