How to check if string contains substring in Rust
Created
Modified
Using String contains Function
The easiest way to check if a Rust string contains a substring is to use String::contains
method.
The contains method Returns true
if the given pattern matches a sub-slice of this string slice.
fn main() {
let s = "Apple,世界";
// pub fn contains<'a, P>(&'a self, pat: P) -> bool
println!("{}", s.contains("e"));
println!("{}", s.contains("世"));
}
true true
The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.
Using String find Method
Returns the byte index of the first character of this string slice that matches the pattern.
Returns None if the pattern doesn’t match.
fn main() {
let s = "Löwe";
if s.find('ö') != None {
// Found
println!("Found")
}
println!("{:?}", s.find('ö'));
println!("{:?}", s.find('o'));
}
Found Some(1) None
Using String chars Method
You can use chars method to check if the string contains at least one lowercase alphabet character.
fn main() {
let s = "Löwe";
let b = s.chars().any(|c| c.eq(&'ö'));
println!("{}", b);
}
true