Rust Reference ยท Strings and Text
Rust str::find, contains and starts_with
Reference for Rust str::find, rfind, contains, starts_with, ends_with, matches and match_indices: patterns, byte offsets and Unicode behavior.
Searching a str uses the same idea everywhere: you give a pattern, and the method tells you whether and where it matches. contains, starts_with and ends_with answer yes or no. find and rfind return the byte offset of the first or last match as an Option<usize>. matches and match_indices iterate over every match.
A pattern can be a char, a &str, a &String, an array or slice of chars (any of them matches), or a closure FnMut(char) -> bool. Matching is exact and case-sensitive.
let s = "hello world"; assert!(s.contains("lo w")); assert_eq!(s.find('o'), Some(4));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn contains<P: Pattern>(&self, pat: P) -> bool fn starts_with<P: Pattern>(&self, pat: P) -> bool fn ends_with<P: Pattern>(&self, pat: P) -> bool fn find<P: Pattern>(&self, pat: P) -> Option<usize> fn rfind<P: Pattern>(&self, pat: P) -> Option<usize> fn matches<P: Pattern>(&self, pat: P) -> Matches<'_, P> fn match_indices<P: Pattern>(&self, pat: P) -> MatchIndices<'_, P>
| Name | Description |
|---|---|
pat |
The pattern to look for: char, &str, [char; N], &[char], or a char closure. |
Returns: bool for the three tests. find and rfind return Some(byte_index) of the start of the match, or None. matches yields the matched &str slices; match_indices yields (usize, &str) pairs. The r variants (rmatches, rmatch_indices) go from the end.
Errors / panics / edge cases: nothing panics. An empty pattern matches everywhere: "abc".find("") is Some(0) and "abc".contains("") is true. starts_with and ends_with with a char closure or char set test only the first or last character.
Usage notes
- Offsets are bytes. The index from
findis always on a character boundary, so it is safe to slice with&s[i..], but it is not a character count. For a character position uses.chars().position(..). - Case-sensitive. For a case-insensitive test, compare
to_lowercase()copies (seeto_uppercaseandto_lowercase) oreq_ignore_ascii_casefor ASCII. - Non-overlapping matches.
"aaaa".matches("aa")finds two matches, not three. - Prefer
containsoverfind(..).is_some(); it states the intent and is equally fast. - Searching for a single
charis optimized (it can use byte search for ASCII). Searching a&struses a two-way algorithm, linear time in the text. - Slices and
Vecs have a differentcontainsthat tests for an element equal to the argument. For text use thesestrmethods, ors.as_bytes().contains(&b'x')for a byte. - Need the rest of the string? Use
split_onceorstrip_prefixinstead of computing offsets by hand. - Regex is not in
std; build simple matchers from char closures.
Related
split,replace,chars, String slicing- Lessons: Strings, Strings overview