
Problem
Solution
Submissions
Check if String Contains Substring
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to check if a given string contains a specific substring. The function should return true if the substring is found within the main string, and false otherwise. The search should be case-sensitive, and you should implement this without using the built-in includes() method or indexOf() method.
Example 1
- Input: mainString = "Hello World Programming", substring = "World"
- Output: true
- Explanation:
- Start searching from index 0 of the main string.
- Compare characters: H≠W, e≠W, l≠W, l≠W, o≠W, space≠W.
- At index 6, find 'W' which matches the first character of "World".
- Continue matching: W=W, o=o, r=r, l=l, d=d - all characters match.
- Complete substring "World" found at index 6, return true.
- Start searching from index 0 of the main string.
Example 2
- Input: mainString = "JavaScript is awesome", substring = "Python"
- Output: false
- Explanation:
- Search through the entire main string for "Python".
- Check each possible starting position but no complete match found.
- 'P' character is not present anywhere in "JavaScript is awesome".
- Since no starting character matches, the substring is not present.
- Return false as "Python" is not found in the main string.
- Search through the entire main string for "Python".
Constraints
- 1 ≤ mainString.length ≤ 1000
- 1 ≤ substring.length ≤ 100
- Both strings contain only ASCII characters
- Search is case-sensitive
- Time Complexity: O(n*m) where n is main string length and m is substring length
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use nested loops to check every possible starting position in the main string
- For each starting position, compare characters of substring with main string
- If all characters match consecutively, return true
- If any character doesn't match, move to the next starting position
- Check boundary conditions to avoid index out of bounds errors
- If no complete match is found after checking all positions, return false
- Handle edge case where substring is longer than main string