← All languages
Rust function of the day

str::starts_with

Check if a string starts with a given pattern.

Description

The starts_with method on str returns true if the string begins with the given pattern. The pattern can be a &str, a char, a char slice, or a closure.

This is more efficient than using split or contains for prefix checking because it only examines the beginning of the string. It runs in O(m) time where m is the length of the pattern.

For checking suffixes, use ends_with.

Arguments

NameDescriptionOptional
pattern The pattern to check at the beginning of the string. No

Example

assert!("Hello, world!".starts_with("Hello"));
assert!("Hello, world!".starts_with('H'));
assert!(!"Hello, world!".starts_with("world"));

Reference