I am trying to find the count of the substring in a big string of length 10000 characters. Finally I need to remove all the substring in it.
example s = abacacac, substr = ac
, num of occurrence = 3
and final string is s = ab
. My code is below, its not efficient for data of length 10000 characters.
int count =0;
while(s.contains(substr))
{
s= s.replaceFirst(substr,"");
count++;
}
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.
Approach: The count of sub-strings of length n will always be len – n + 1 where len is the length of the given string.
count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.
There are several ways using which you can count occurrences of substring in Java. You can count occurrences of substring in string using indexOf method of String class.
Substring in Java 1 String substring () : This method has two variants and returns a new string that is a substring of this string. The... 2 String substring (begIndex, endIndex): This method has two variants and returns a new string that is a substring of... More ...
The indexOf () method in java is a specialized function to find the index of the first occurrence of a substring in a string. This method has 4 overloads. We will use the second overload as we have to check the entire string. The fromIndex parameter is used to specify the starting index from where to start the search.
In the while loop, we find the substring, assign the index of next occurrence to fromIndex and check if the returned value is greater than -1. The indexOf method returns -1 if the substring is not found in the string, otherwise, it returns the index of the substring. Inside the while loop, we increment the count of occurrence of substring.
What about:
String temp = s.replace(sub, "");
int occ = (s.length() - temp.length()) / sub.length();
Just remove all the substring, then check the difference on string length before and after removal. Divide the temp string with number of characters from the substring gives you the occurrences.
For countung the substrings I would use indexOf:
int count = 0;
for (int pos = s.indexOf(substr); pos >= 0; pos = s.indexOf(substr, pos + 1))
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