Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let s = "hello world";
assert!(s.contains("lo w"));
assert_eq!(s.find('o'), Some(4));

Try it

Rust Yes/no questions and positions

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.

Rust All matches and byte offsets

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

Rust
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 find is 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 use s.chars().position(..).
  • Case-sensitive. For a case-insensitive test, compare to_lowercase() copies (see to_uppercase and to_lowercase) or eq_ignore_ascii_case for ASCII.
  • Non-overlapping matches. "aaaa".matches("aa") finds two matches, not three.
  • Prefer contains over find(..).is_some(); it states the intent and is equally fast.
  • Searching for a single char is optimized (it can use byte search for ASCII). Searching a &str uses a two-way algorithm, linear time in the text.
  • Slices and Vecs have a different contains that tests for an element equal to the argument. For text use these str methods, or s.as_bytes().contains(&b'x') for a byte.
  • Need the rest of the string? Use split_once or strip_prefix instead of computing offsets by hand.
  • Regex is not in std; build simple matchers from char closures.