gpt4 book ai didi

string - 拆分字符串并跳过空子字符串

转载 作者:行者123 更新时间:2023-12-03 11:25:21 26 4
gpt4 key购买 nike

我正在学习 Rust 并发现了这个问题:
我想按模式拆分字符串并删除结果子字符串为空的所有情况。
下面是一个例子:

let s = "s,o,m,e,";
for elem in s.split(",").skip_while(|&x| x.is_empty()) {
print!(" <{}> ", elem);
//print!(" <{}>({}) ", elem, elem.is_empty());
}
但结果如下:
 <s>  <o>  <m>  <e>  <> 
我的想法是: Split 返回的 struct split 实现了提供 Iteratorskip_while 。 IntelliSense 告诉我闭包中的 x&&str 类型,所以我假设迭代器(类型 &str )的所有元素都是空的被省略。
但它不会跳过空子字符串。
我还尝试打印 is_empty 函数的结果。它表明最后一个切片确实是空的。如果我代替 skip_while 使用 skip_while(|&x| x == "s") ,它会正确地忽略 "s" (在此处使用 is_empty 打印):
 <o>(false)  <m>(false)  <e>(false)  <>(true)
那么切片在迭代器中的行为不同吗?
为什么会这样或者我在哪里弄错了?

最佳答案

如果您只需要省略输入末尾的 1 个空字符串,只需使用 split_terminator 而不是 split 。这个适配器基本上就像 split 一样,但它将模式参数视为终止符而不是分隔符,因此输入末尾的空字符串不被视为新元素。
如果您真的想跳过所有空字符串,请继续阅读。

skip_while 完全按照其文档中的说明进行操作(重点是我的):

skip_while() takes a closure as an argument. It will call this closure on each element of the iterator, and ignore elements until it returns false.

After false is returned, skip_while()'s job is over, and the rest of the elements are yielded.


过滤掉与谓词匹配的所有元素,无论它们在序列中的哪个位置,都是 filter 的工作:
let s = ",s,o,,m,e,";
for elem in s.split(",").filter(|&x| !x.is_empty()) {
print!(" <{}> ", elem);
}
上面的代码就会有你想要的效果。
请注意, filter 的谓词与 skip_while 具有相反的含义:不是为不应产生的元素返回 true,而是为应产生的元素返回 true

关于string - 拆分字符串并跳过空子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63362027/

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