Find Substring with contains()
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
hello world does not contain xyz
Case sensitive: Test != test
hello world contains world
Empty substring is always found
Contains rust
Algorithm Flow

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