Check if a string starts with a given pattern.
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.
| Name | Description | Optional |
|---|---|---|
pattern |
The pattern to check at the beginning of the string. | No |
assert!("Hello, world!".starts_with("Hello"));
assert!("Hello, world!".starts_with('H'));
assert!(!"Hello, world!".starts_with("world"));