Rust为字符串提供了一个trim方法:trim()删除前导和尾随空格。我想有一个方法,对字节串做同样的事情。它应该接受一个Vec<u8>
并删除前导和尾随空格(空格,0x20和htab,0x09)。
编写trim_left()
很容易,你可以使用skip_while()
的迭代器:Rust Playground
fn main() {
let a: &[u8] = b" fo o ";
let b: Vec<u8> = a.iter().map(|x| x.clone()).skip_while(|x| x == &0x20 || x == &0x09).collect();
println!("{:?}", b);
}
但是要修剪正确的字符,如果在发现空白之后列表中没有其他字母,我需要向前看。
4条答案
按热度按时间f45qwnt81#
下面的实现返回一个切片,而不是像
str::trim()
那样返回一个新的Vec<u8>
。它也在[u8]
上实现,因为它比Vec<u8>
更通用(您可以从向量中廉价地获得切片,但从切片创建向量的成本更高,因为它涉及堆分配和副本)。如果在
trim()
之后确实需要一个Vec<u8>
,则只需在切片上调用into()
将其转换为Vec<u8>
。a0x5cqrl2#
这是一个比其他答案简单得多的版本。
奇怪的是,这不是在标准库。我会认为这是一个共同的任务。
无论如何,这里是一个完整的文件/trait(带有测试!),您可以复制/粘贴。
bsxbgnwa3#
我们所要做的就是找到第一个非空格字符的索引,一次从开始向前计数,另一次从结束向后计数。
nhaq1z214#
结合Francis Gagné和Timmmm给出的解,我们有:
参见Rust Playground