Find Substring in String
C++
Medium
4 views
Problem Description
Check if one string exists inside another string.
Real Life: Search functionality in text.
Step-by-Step Logic:
1. For each position in main string
2. Check if substring matches from that position
3. Compare character by character
4. Return position if found
Official Solution
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;
}
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!