+ 2

Wap to find the no of occurrence of sub string in a given string.

For example Str="This is a small island" Substr="is" Then output should be : 3 (as is occured 3 times in first string).

29th Dec 2018, 9:15 AM
Ravindra
Ravindra - avatar
3 Réponses
+ 10
I have done it with string, you can do this with char array too but in that you have to define size before runtime but in string that's not the case. #include <iostream> #include <cstring> #include <string> using namespace std; int main() { string str = "This is small island"; string subStr = "is"; int strLen = str.length(); int subStrLen = subStr.length(); int indexCount = 0, timesFound = 0; bool isFound = false; for(int i = 0; i < strLen; i++) { if(subStr[indexCount] == str[i]) { indexCount++; if(indexCount == subStrLen) { isFound = true; } } else { indexCount = 0; } if(isFound) { timesFound++; isFound = false; indexCount = 0; } } cout << "Substring \"" << subStr << "\" was found " << timesFound << " times in the string \"" << str << "\"\n"; }
29th Dec 2018, 11:29 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 9
Try to show your attempt please. If there is any issue, I would try to correct and show it then.
29th Dec 2018, 9:26 AM
Calviղ
Calviղ - avatar
+ 1
Thank u
29th Dec 2018, 3:49 PM
Ravindra
Ravindra - avatar