Total number of substrings = n + (n - 1) + (n - 2) + (n - 3) + (n - 4) + ……. + 2 + 1. So now we have a formula for evaluating the number of substrings where n is the length of a given string.
Find indices of all occurrence of one string in other in C++ To solve this problem, we can use the substr() function in C++ STL. This function takes the initial position from where it will start checking, and the length of the substring, if that is the same as the sub_str, then returns the position.
Python String count() Method Python String count() function is an inbuilt function in python programming language that returns the number of occurrences of a substring in the given string. Parameters: The count() function has one compulsory and two optional parameters.
How about using StringUtils.countMatches from Apache Commons Lang?
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
That outputs:
3
Your lastIndex += findStr.length();
was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always to findStr.length()
).
Here is the fixed version :
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += findStr.length();
}
}
System.out.println(count);
A shorter version. ;)
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);
The last line was creating a problem. lastIndex
would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With