Mag*_*gix 3 regex whitespace removing-whitespace rust
如何从字符串中删除所有空格?我可以想到一些显而易见的方法,例如遍历字符串并删除每个空白字符,或使用正则表达式,但是这些解决方案并不那么具有表现力或效率。什么是从字符串中删除所有空格的简单有效的方法?
Mag*_*gix 13
一个不错的选择是使用split_whitespace然后收集到一个字符串:
fn remove_whitespace(s: &str) -> String {
s.split_whitespace().collect()
}
Run Code Online (Sandbox Code Playgroud)
如果要修改String,请使用retain。如果可能的话,这可能是最高效的方法。
fn remove_whitespace(s: &mut String) {
s.retain(|c| !c.is_whitespace());
}
Run Code Online (Sandbox Code Playgroud)
如果由于仍然需要或仅具有一个而无法修改它&str,则可以使用filter并创建一个新的String。当然,必须分配才能制作String。
fn remove_whitespace(s: &str) -> String {
s.chars().filter(|c| !c.is_whitespace()).collect()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
816 次 |
| 最近记录: |