str::contains¶
Level: reference · for working programmers
One line: true if the pattern occurs anywhere — the readable form of find(..).is_some().
Stable since 1.0.0.
The argument is a pattern, which is four things: a char, a &str, a &[char] (any of these characters), or a closure FnMut(char) -> bool. That one trait is why the search, split, trim and replace families all take the same shapes.
It stops at the first match, so a hit is cheap and a miss costs a full scan.
It is a byte-level search, not a linguistic one. "Hello".contains("hello") is false; for case-insensitive matching lowercase both sides first, and know that this is only correct for ASCII — see to_lowercase. Text that can be spelled two ways in Unicode (é as one scalar or as e plus a combining accent) will not match across spellings, because nothing here normalizes.
An empty pattern is contained in everything, including the empty string.
Example¶
str_contains.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let s = "the quick brown fox";
println!("{}", s.contains("quick")); // &str
println!("{}", s.contains('q')); // char
println!("{}", s.contains(&['x', 'z'][..])); // any of these chars
println!("{}", s.contains(char::is_numeric)); // a predicate
// Byte-level, not linguistic.
println!("{}", "Hello".contains("hello"));
println!("{}", "Hello".to_lowercase().contains("hello"));
// Two spellings of the same visible text do not match each other.
println!("{}", "café".contains("é"));
println!("{}", "cafe\u{301}".contains("é"));
// The empty pattern is everywhere.
println!("{} {}", s.contains(""), "".contains(""));
}
Verified output of str_contains.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::find— the same search, returning wherestr::starts_with— anchored at the frontstr::ends_with— anchored at the backstr::matches— every occurrence, not just whether there is one
str::contains in the standard library ↗
Po polsku¶
contains to czytelniejsza forma find(..).is_some(), a jej argument jest wzorcem (Pattern) w czterech postaciach: char, &str, &[char] („którykolwiek z tych znaków”) i domknięcie FnMut(char) -> bool. Dla polskiego tekstu najważniejsze jest jednak to, że porównanie idzie bajt po bajcie, a nie językowo: "Łódź".contains("łódź") to false, a jeśli zmniejszasz wielkość liter po obu stronach, sięgnij po to_lowercase(), nie po to_ascii_lowercase() — ta druga zostawi Ł i Ó nietknięte, bo nie są znakami ASCII. Drugiej pułapki nie widać wcale: nic tu nie normalizuje, więc ź zapisane jednym skalarem nie dopasuje się do z z łączącym akcentem, choć na ekranie wyglądają identycznie — dane z różnych źródeł trzeba znormalizować wcześniej, np. crate'em unicode-normalization.
Szukaj po polsku: wyszukiwanie podłańcucha · wzorzec Pattern w Ruscie · normalizacja Unicode · rust str contains case insensitive · rust unicode-normalization