MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Find Substring in String with Explanation

C++ Medium Strings 33 views
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around found, search, substring. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Check if one string exists inside another string.
Real Life: Search functionality in text.

Input Format

Two strings:

• str1 → main string

• str2 → string to search

Output Format

Print

• Found
OR

• Not Found

Constraints

• Strings length ≥ 1

• Case-sensitive

• Use basic string logic

Concept Explanation

We need to check whether str2 exists inside str1.
This is like a search feature in text editors or websites.

Step-by-Step Logic

1.Take input strings str1 and str2.

2.Get lengths of both strings.

3.Loop through str1 from index 0 to (len1 - len2).

4.For each position, compare characters of str2 with str1.

5.If all characters match at any position:

• Print Found.

6.If no match is found after full loop:

• Print Not Found.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
void string_q9_find_substring() { string mainStr = "Programming in C plus plus"; string subStr = "plus"; int found = -1; for(int i = 0; i <= mainStr.length() - subStr.length(); i++) { bool match = true; for(int j = 0; j < subStr.length(); j++) { if(mainStr[i + j] != subStr[j]) { match = false; break; } } if(match) { found = i; break; } } if(found != -1) { cout << "Substring found at position: " << found << endl; } else { cout << "Substring not found" << endl; } }

Output Example

Input:
programming is fun is
Output:
Found

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next