+ 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).
3 Answers
+ 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";
}
+ 9
Try to show your attempt please. If there is any issue, I would try to correct and show it then.
+ 1
Thank u