I have a string, say "dog cat fish", that I want to split on the first whitespace into two slices that look like this: ("dog", "cat fish").
I tried to naively use the split_once() method like this:

let string = "dog cat fish";
let (first_word, rest_of_string) = string.split_once(' ').unwrap();

It works effectively for regular whitespace characters. However, I would like it to work also for other types of Unicode whitespace characters like \t as the split_whitespace() method does.
I don't want to use split_whitespace(), though, because it returns an iterator and I would have to recollect and join the words after iterating, as it would be a waste of time:

let mut it = string.split_whitespace();
let first_word = it.next().unwrap();
let rest_of_string = it.collect::Vec<&str>().join(" ");

So, in case I had a string like "dog \t cat fish", how could I split it to obtain these two slices ("dog", "cat fish")?
I also thought of using regular expressions, but is there a better method?

推荐答案

您可以使用调用char::is_whitespace()的函数为split_once,但这只会在第一个空格上拆分.然后,您需要从开始处修剪第二个&str.

fn main() {
    let string = "dog \t cat fish";
    let (a, b) = string.split_once(char::is_whitespace).unwrap();
    let b = b.trim_start();
    dbg!(a, b);
}

输出:

[src/main.rs:5] a = "dog"
[src/main.rs:5] b = "cat fish"

Playground

Rust相关问答推荐

阻止websocket中断的中断中断的终端(操作系统错误4)

当为a Self:IntoIterator设置trait bind `时,获取`a T `不是迭代器"&'"<'>&'

在actix—web中使用Redirect或NamedFile响应

包含嵌套 struct 的CSV

从Rust调用C++虚拟方法即使在成功执行之后也会引发Access违规错误

有没有办法模仿对象安全克隆?

值为可变对象的不可变HashMap

为什么BitVec缺少Serialize trait?

这个规则关于或模式到底是什么意思?如果表达片段的类型与p_i|q_i...&q;不一致,就会形成

为什么reqwest以文本形式下载二进制文件?

铁 rust 中的共享对象实现特征

如何导入crate-type=[";cdylib;]库?

为什么`AlternateScreen`在读取输入键时需要按Enter键?

如何轮询 Pin>?

在使用粗粒度锁访问的数据 struct 中使用 RefCell 是否安全?

为什么 Rust 创建的 f32 小于 f32::MIN_POSITIVE?

一旦令牌作为文字使用,声明宏不匹配硬编码值?

在不安全的 Rust 中存储对 struct 内部数据的静态引用是否合法?

如何异步记忆选项中的 struct 字段

为什么分配对变量的引用使我无法返回它