Code Logo

Find Substring with contains()

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 contains the second substring using the contains() method. The contains() method checks whether a pattern appears anywhere in the string and returns a boolean.

The contains() method is defined on str and works with both string slices and String types. It performs a simple substring search using Rust's pattern API. The method is case-sensitive by default, meaning 'A' and 'a' are treated as different characters. The search scans from left to right and returns as soon as the first match is found.

Rust's contains() is part of a family of pattern-searching methods including starts_with(), ends_with(), find(), and matches(). These methods accept any type that implements the Pattern trait, including &str, char, and closures. This design makes the pattern API flexible and composable.

Time complexity is O(n * m) in the worst case where n is the haystack length and m is the needle length, though the implementation uses efficient substring search algorithms. Space complexity is O(1) as no additional allocation is needed.

Edge cases include empty substring (returns true for any string), case sensitivity (upper vs lowercase differences), substring at the start, middle, or end of the string, and substring longer than the string (returns false).

Example Input & Output

Example 1
Input
"hello world","xyz"
Output
false
Explanation

hello world does not contain xyz

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

Case sensitive: Test != test

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

hello world contains world

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

Empty substring is always found

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

Contains rust

Algorithm Flow

Recommendation Algorithm Flow for Find Substring with contains()
Recommendation Algorithm Flow for Find Substring with contains()

Solution Approach

fn solution(s: &str, sub: &str) -> bool {
    s.contains(sub)
}

Best Answers

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