如何从字符串中删除所有空格?我可以想到一些明显的方法,比如循环遍历字符串并删除每个空格字符,或者使用正则表达式,但这些解决方案不够简洁高效。有什么简单而高效的方法可以从字符串中删除所有空格?
如何从字符串中删除所有空格?我可以想到一些明显的方法,比如循环遍历字符串并删除每个空格字符,或者使用正则表达式,但这些解决方案不够简洁高效。有什么简单而高效的方法可以从字符串中删除所有空格?
如果您想修改String
,请使用retain
。这可能是可用时最快的方法。
fn remove_whitespace(s: &mut String) {
s.retain(|c| !c.is_whitespace());
}
如果因为你仍然需要它或者只有一个&str
而无法修改它,那么可以使用 filter 并创建一个新的String
。当然,这将需要分配内存来创建 String
。
fn remove_whitespace(s: &str) -> String {
s.chars().filter(|c| !c.is_whitespace()).collect()
}
split_whitespace
函数然后将其收集到一个字符串中:fn remove_whitespace(s: &str) -> String {
s.split_whitespace().collect()
}
split_whitespace
不会消耗字符串,因此将函数接收一个字符串切片是正确的做法。collect
将从字符迭代器创建一个String
,但这将是任何一种方式中唯一的分配。 - E net4实际上,我找到了一个更简洁的方法。
fn no_space(x : String) -> String{
x.replace(" ", "")
}
is_whitespace()
函数来找到它们。 - Magixremove_matches()
方法。#![feature(string_remove_matches)]
fn remove_whitespace(s: &mut String) {
s.remove_matches(char::is_whitespace);
}
有些令人惊讶的是,根据我进行的(非常不精确的)小型基准测试,它始终比retain()
更快。
trim()
函数来去除空格、制表符和换行符等空白字符。fn remove_space(data: &str) {
for word in data.split(",") {
println!("{:?}", word.trim());
}
}
replace
就可以返回第三个条目std::str::replace
,它也可以很好地完成工作。这是一种可能会变得有用的问题,但需要时间来证明其有用性。 - E net4