gpt4 book ai didi

rust - 拆分字符串并保留分隔符

转载 作者:行者123 更新时间:2023-11-29 08:20:54 26 4
gpt4 key购买 nike

是否有一种简单的方法来拆分保留分隔符的字符串?而不是这个:

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

我想要一些能给我的东西:

[“十”、“.”、“”、“百万”、“.”、“”、“问题”、“.”、“”、“让我们”、“”、“庆祝” , "", "all", "", "we've", "", "done", "", "together", "."].

我正在尝试那种代码(它假定字符串以字母开头并以“非”字母结尾):

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看起来很粗糙。

最佳答案

使用 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);

打印:

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

关于rust - 拆分字符串并保留分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com