retain Filters Chars From Strings In Place
Drop unwanted chars from a String in place with retain: char-safe iteration, no new allocation, and the original buffer is reused across passes.
Code
fn main() {
// 混入数字与空白的产品编码:就地把它们过滤掉
let mut code = String::from("AB-12 c3 d");
let before = code.chars().count();
// retain 按 char 遍历:多字节字符安全,且不产生新分配
code.retain(|c| c.is_ascii_alphabetic() || c == '-');
println!("kept {before} -> {} chars: {code}", code.chars().count());
// 二次 retain:条件变了就再过滤一遍,原缓冲区复用
code.retain(|c| c != '-');
println!("dashes dropped: {code}");
// 对照:filter + collect 会分配新 String,retain 是原地改写
let rebuilt: String = "x9y".chars().filter(|c| c.is_ascii_alphabetic()).collect();
println!("collect rebuilt: {rebuilt}");
}Inside the snippet
retain Filters Chars From Strings In Place is built around the function main.
Putting it to use
Running the file prints labeled results such as kept, dashes dropped:, collect rebuilt: — each operation’s effect is visible in the output.
Core lines
let rebuilt: String = "x9y".chars().filter(|c| c.is_ascii_alphabetic()).collect();
Interactive Tools for This Topic
FAQ
- What does retain Filters Chars From Strings In Place print when run?
- No setup needed: run the file and look for labeled lines like `kept`, `dashes dropped:`, `collect rebuilt:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.