Code Logo

Check Prefix with starts_with()

Published at25 Jul 2026
Rust String Handling Easy 0 views
Like0

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

Example 1
Input
"rust programming","rust"
Output
true
Explanation

Starts with rust

Example 2
Input
"hello world","hello"
Output
true
Explanation

hello world starts with hello

Example 3
Input
"hello world","world"
Output
false
Explanation

Does not start with world

Example 4
Input
"abc","abc"
Output
true
Explanation

Exact match

Example 5
Input
"test","Test"
Output
false
Explanation

Case sensitive

Algorithm Flow

Recommendation Algorithm Flow for Check Prefix with starts_with()
Recommendation Algorithm Flow for Check Prefix with starts_with()

Solution Approach

fn solution(s: &str, prefix: &str) -> bool {
    s.starts_with(prefix)
}

Best Answers

rust - Approach 1
fn solution(s: &str, prefix: &str) -> bool {
    s.starts_with(prefix)
}