Skip to content

Commit 0cffb41

Browse files
committed
added string retain example
1 parent f5a5b26 commit 0cffb41

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

string-retain/Cargo.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "string-retain"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]

string-retain/src/main.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
fn retain<F>(s: &mut String, mut pred: F)
2+
where F: FnMut(char) -> bool
3+
{
4+
let mut nretained = 0;
5+
for c in s.chars() {
6+
if pred(c) {
7+
nretained += 1;
8+
}
9+
}
10+
let mut result = String::with_capacity(nretained);
11+
for c in s.chars() {
12+
if pred(c) {
13+
result.push(c);
14+
}
15+
}
16+
*s = result;
17+
}
18+
19+
fn main() {
20+
let mut s = "Hello, world!".to_string();
21+
let mut copy_of_s = s.clone();
22+
let is_vowel = |c| "aieou".contains(c);
23+
copy_of_s.retain(is_vowel);
24+
println!("{}", copy_of_s);
25+
retain(&mut s, is_vowel);
26+
println!("{}", s);
27+
}

0 commit comments

Comments
 (0)