Occurrences of substring in a string
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);
How to find the count of substring in java
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.
How to count number of occurrences of a substring inside a string in Python?
you can use count
print("hellohel".count("hel"))
2
If you want to count overlapping occurrences... maybe this can help
def countOverlapping(string, item):
count = 0
for i in range(0,len(string)):
if item in string[i:len(item)+i]:
count += 1
return count
print(countOverlapping("ehehe", "ehe"))
output should be...
2
How does that work?
as @SomeDude mentioned it uses what he calls a sliding window approach
we take the length of the substring and check if its in that "window" of the string each iteration:
is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1
How to count of sub-string occurrences?
Regex.Matches(input, "OU=").Count
Finding number of times a substring exists in a string - Python
You seem to want overlapping counts. str.count
will not get you there, unfortunately, because it does not overlap substring searches. Try slicing and counting.
Here's a solution with a collections.Counter
though it can be done just about any other way as long as you slice it right.
from collections import Counter
text = 'bobbisbobobugbobobbobbobo'
term = 'bob'
c = Counter([text[i : i + len(term)] for i in range(len(text))])
print(c[term])
7
How to find all occurrences of a substring?
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]
If you want to find overlapping matches, lookahead will do that:
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]
re.finditer
returns a generator, so you could change the []
in the above to ()
to get a generator instead of a list which will be more efficient if you're only iterating through the results once.
Find all occurrences of substring in string in Java
You can use capturing inside a positive look-ahead to get all overlapping matches and use Matcher#start
to get the indices of the captured substrings.
As for the regex, it will look like
(?=(aa))
In Java code:
String s = "aaaaaa";
Matcher m = Pattern.compile("(?=(aa))").matcher(s);
List<Integer> pos = new ArrayList<Integer>();
while (m.find())
{
pos.add(m.start());
}
System.out.println(pos);
Result:
[0, 1, 2, 3, 4]
See IDEONE demo
Number of occurrences of substring in string in Swift
A simple approach would be to split on "Swift"
, and subtract 1 from the number of parts:
let s = "hello Swift Swift and Swift"
let tok = s.components(separatedBy:"Swift")
print(tok.count-1)
This code prints 3.
Edit: Before Swift 3 syntax the code looked like this:
let tok = s.componentsSeparatedByString("Swift")
Related Topics
Syntax For Creating a Two-Dimensional Array in Java
How to Get X and Y Index of Element Inside Gridlayout
Spring Boot Configure and Use Two Data Sources
Received Fatal Alert: Handshake_Failure Through Sslhandshakeexception
How Does a Java Hashmap Handle Different Objects With the Same Hash Code
Are Getters and Setters Poor Design? Contradictory Advice Seen
How to Sanity Check a Date in Java
How to Fix Dagger 2 Error '... Cannot Be Provided [...]'
Are Fields Initialized Before Constructor Code Is Run in Java
Spring - @Transactional - What Happens in Background
Try/Catch With Inputmismatchexception Creates Infinite Loop
Spring @Transactional Not Auto Rolling Back During Unchecked Exception