Count the number of occurrences of a character in a string
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring
sub
in the range[start, end]
. Optional argumentsstart
andend
are interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
How to count string occurrence in string?
The g
in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is
twice:
var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);
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 do I count the number of occurrences of a char in a String?
My 'idiomatic one-liner' for this is:
int count = StringUtils.countMatches("a.b.c.d", ".");
Why write it yourself when it's already in commons lang?
Spring Framework's oneliner for this is:
int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
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
Count occurrences of a substring in a list of strings
You can do this by using the sum
built-in function. No need to use list.count
as well:
>>> data = ["the foo is all fooed", "the bar is all barred", "foo is now a bar"]
>>> sum('foo' in s for s in data)
2
>>>
This code works because booleans can be treated as integers. Each time 'foo'
appears in a string element, True
is returned. the integer value of True
is 1
. So it's as if each time 'foo'
is in a string, we return 1
. Thus, summing the 1
's returned will yield the number of times 1
appeared in an element.
A perhaps more explicit but equivalent way to write the above code would be:
>>> sum(1 for s in data if 'foo' in s)
2
>>>
Count the number of occurrences of a character in a string in Javascript
I have updated this answer. I like the idea of using a match better, but it is slower:
console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
How would you count occurrences of a string (actually a char) within a string?
If you're using .NET 3.5 you can do this in a one-liner with LINQ:
int count = source.Count(f => f == '/');
If you don't want to use LINQ you can do it with:
int count = source.Split('/').Length - 1;
You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:
Your original = 12s
source.Count = 19s
source.Split = 17s
foreach (from bobwienholt's answer) = 10s
(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)
Related Topics
Create a Date With a Set Timezone Without Using a String Representation
How to Write a Countdown Timer in JavaScript
How to Use Backslashes (\) in a String
Incrementing a Date in JavaScript
Resetting the Opacity of a Child Element - Maple Browser (Samsung Tv App)
Dynamically Expand Height of Input Type "Text" Based on Number of Characters Typed into Field
Why Does the Setinterval Callback Execute Only Once
Why Don't Logical Operators (&& and ||) Always Return a Boolean Result
How to Check If File Exists in Jquery or Pure JavaScript
For Loop For Htmlcollection Elements
Suppress Chrome 'Failed to Load Resource' Messages in Console
Is It Not Possible to Stringify an Error Using Json.Stringify
Jquery Event That Triggers After CSS Is Loaded
Flex Items Not Shrinking When Window Gets Smaller
Event Listener on a CSS Pseudo-Element, Such as ::After and ::Before