我希望能够分离bbcc上的字符串aabbaacaaaccaaa,但不能分离bc上的字符串.这个例子的结果是aa,aacaaa,aaa.

我已经可以在一个分隔符上拆分字符串,words()函数可以在\n\t上拆分字符串,所以我认为这是可能的.

推荐答案

不幸的是,你现在不能这么做.不过,您可以在多个char分隔符上拆分can,就像words一样.你需要给split个字符分配一个片段:

for part in "a,bc;d".split(&[',', ';'][..]) {
    println!(">{}<", part);
}

但是,如果您try 使用字符串:

for part in "a,bc;d".split(&[",", ";"][..]) {
    println!(">{}<", part);
}

您将得到以下错误:

error[E0277]: expected a `Fn<(char,)>` closure, found `[&str]`
 --> src/main.rs:2:32
  |
2 |     for part in "a,bc;d".split(&[",", ";"][..]) {
  |                                ^^^^^^^^^^^^^^^ expected an `Fn<(char,)>` closure, found `[&str]`
  |
  = help: the trait `Fn<(char,)>` is not implemented for `[&str]`
  = note: required because of the requirements on the impl of `FnOnce<(char,)>` for `&[&str]`
  = note: required because of the requirements on the impl of `Pattern<'_>` for `&[&str]`

在nightly Rust中,您可以为自己的类型实现Pattern,其中包括一段字符串.

如果您对使用标准库之外的支撑良好的 crate 很满意,您可以使用regex:

use regex; // 1.4.5

fn main() {
    let re = regex::Regex::new(r"bb|cc").unwrap();
    for part in re.split("aabbaacaaaccaaa") {
        println!(">{}<", part);
    }
}

Rust相关问答推荐

Tauri tauri—apps/plugin—store + zustand

如果A == B,则将Rc A下推到Rc B

当rust中不存在文件或目录时,std::FS::File::Create().unwire()会抛出错误

有没有更好的方法从HashMap的条目初始化 struct ?

如果LET;使用布尔表达式链接(&Q);

如果死 struct 实现了/派生了一些特征,为什么Rust会停止检测它们?

用于判断整数块是否连续的SIMD算法.

你能在Rust中弃用一个属性吗?

减少指示ProgressBar在Rust中的开销

`actix-web` 使用提供的 `tokio` 运行时有何用途?

如何在 Rust 中打印 let-else 语句中的错误?

Rust中是否可以在不复制的情况下从另一个不可变向量创建不可变向量?

Rust中如何实现一个与Sized相反的负特性(Unsized)

实现AsyncWrite到hyper Sender时发生生命周期错误

rust 中不同类型的工厂函数

匹配结果时的简洁日志(log)记录

BigUint 二进制补码

如何将 while 循环内的用户输入添加到 Rust 中的向量?

为什么这里需要类型注解?

有没有比多个 push_str() 调用更好的方法将字符串链接在一起?