File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change
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 ]
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments