C++ Program to Find substring in a String
Here you will get and learn the source code of C++ program to find substring in a string.
Example of C++ program to find substring in a string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | //C++ Program to Find Substring in String //Pattern Matching #include <iostream> #include <string.h> using namespace std; int main() { char str1[100], str2[20]; int count1 = 0, count2 = 0, i, j, flag; cout << "Enter a string: "; gets(str1); cout << "Enter search sub-string: "; cin >> str2; while (str1[count1] != '\0') count1++; while (str2[count2] != '\0') count2++; for (i = 0; i <= count1 - count2; i++) { for (j = i; j < i + count2; j++) { flag = 1; if (str1[j] != str2[j - i]) { flag = 0; break; } } if (flag == 1) break; } if (flag == 1) { cout << "Sub-String found :) "; } else cout << "Sub-String not found :( "; return 0; } |
Output 1
Enter a string: I am learning c++ from coderevise.com
Enter substring to search : c++
Sub-String found 🙂
Output 2
Enter a string: I am learning c++ from coderevise.com
Enter substring to search : Java
Sub-String not found 🙁
Check out our other C++ programming Examples