Check Prefix with starts_with()
Write a Rust function that takes two string slices (&str) and returns true if the first string starts with the second using the starts_with() method. The starts_with() method checks whether a string begins with a given pattern and returns a boolean.
The starts_with() method is defined on str and works with both string slices and String types. It is part of Rust's pattern API which also includes ends_with(), contains(), find(), and matches(). These methods accept any type that implements the Pattern trait, providing a consistent interface for string searching operations.
Using starts_with() is more idiomatic in Rust than manually comparing slices with get(..prefix.len()). The method handles edge cases like empty prefix (always returns true) and prefix longer than the string (returns false) automatically. It also works correctly with multi-byte Unicode characters because it operates on the character level, not byte level.
Time complexity is O(m) where m is the length of the prefix, as the method must compare each character. Space complexity is O(1) as no allocation is needed. The comparison is case-sensitive and works on UTF-8 encoded strings without decoding.
Edge cases include empty prefix (returns true for any string), prefix longer than the string (returns false), case sensitivity (upper vs lowercase differences), and ensuring the method works correctly with Unicode characters and special characters.
Example Input & Output
Starts with rust
hello world starts with hello
Does not start with world
Exact match
Case sensitive
Algorithm Flow

Solution Approach
Best Answers
fn solution(s: &str, prefix: &str) -> bool {
s.starts_with(prefix)
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
