拆分字符串保留分隔符 [英] Split a string keeping the separators

查看:61
本文介绍了拆分字符串保留分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以拆分字符串并保留分隔符?而不是这样:

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();

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

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

I would like something that gives me :

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

但是有没有更好的方法来编码?因为我尝试在 v2 上枚举但是没有用,而且在 for 循环中使用 j 看起来很粗糙.

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.

推荐答案

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

这篇关于拆分字符串保留分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆