rustHow do you filter a Rust string?
Filtering a Rust string can be done using the filter()
method. This method takes a closure as an argument and returns a new string with only the characters that satisfy the closure's condition.
Example
let my_string = "Hello World!";
let filtered_string = my_string.filter(|c| c.is_alphabetic());
Output example
HelloWorld
The code above filters the string my_string
and stores the result in filtered_string
. The closure passed to filter()
checks if each character is alphabetic and only keeps those that are.
The parts of the code are:
let my_string = "Hello World!";
: This declares a string variablemy_string
and assigns it the value"Hello World!"
.let filtered_string = my_string.filter(|c| c.is_alphabetic());
: This declares a string variablefiltered_string
and assigns it the result of callingfilter()
onmy_string
. The closure passed tofilter()
checks if each character is alphabetic and only keeps those that are.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to use 'or' in Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use regex to match a group in Rust?
- How to replace all matches using Rust regex?
- How to match the end of a line in a Rust regex?
- How to parse JSON string in Rust?
- How to use regex with bytes in Rust?
See more codes...