Count the Number of Times a String Appears Within a String

Count the number of times a string appears within a string

Regex.Matches(input, "true").Count

Determining how many times a substring occurs in a string in Python

Use str.count:

>>> nStr = '000123000123'
>>> nStr.count('123')
2

A working version of your code:

nStr = '000123000123'
pattern = '123'
count = 0
flag = True
start = 0

while flag:
a = nStr.find(pattern, start) # find() returns -1 if the word is not found,
#start i the starting index from the search starts(default value is 0)
if a == -1: #if pattern not found set flag to False
flag = False
else: # if word is found increase count and set starting index to a+1
count += 1
start = a + 1
print(count)

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.)

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 arguments start and end are interpreted as in slice notation.

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

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

Ruby: How to count the number of times a string appears in another string?

Here are a couple of ways to count the numbers of times a given substring appears in a string (the first being my preference). Note (as confirmed by the OP) the substring 'aa' appears twice in the string 'aaa', and therefore five times in:

str = "aaabbccaaaaddbab"

#1

Use String#scan with a regex that contains a positive lookahead that looks for the substring:

def count_em(str, substr)
str.scan(/(?=#{substr})/).count
end

count_em(str,"aa")
#=> 5
count_em(str,"ab")
#=> 2

Note:

"aaabbccaaaaddbab".scan(/(?=aa)/)
#=> ["", "", "", "", ""]

A positive lookbehind produces the same result:

"aaabbccaaaaddbab".scan(/(?<=aa)/)
#=> ["", "", "", "", ""]

As well, String#scan could be replaced with the form of String#gsub that takes one argument (here the same regular expression) and no block, and returns an enumerator. That form of gsub in unusual in that has nothing to do with character replacement; it simply generates matches of the regular expression.

#2

Convert to an array, apply String#each_char then Enumerable#each_cons, then Enumerable#count:

def count_em(str, substr)
subarr = substr.chars
str.each_char
.each_cons(substr.size)
.count(subarr)
end

count_em(str,"aa")
#=> 5
count_em(str,"ab")
#=> 2

We have:

subarr = "aa".chars
#=> ["a", "a"]
enum0 = "aaabbccaaaaddbab".each_char
#=> #<Enumerator: "aaabbccaaaaddbab":each_char>

We can see the elements that will generated by this enumerator by converting it to an array:

enum0.to_a
#=> ["a", "a", "a", "b", "b", "c", "c", "a", "a", "a",
# "a", "d", "d", "b", "a", "b"]

enum1 = enum0.each_cons("aa".size)
#=> #<Enumerator: #<Enumerator:
# "aaabbccaaaaddbab":each_char>:each_cons(2)>

Convert enum1 to an array to see what values the enumerator will pass on to map:

enum1.to_a
#=> [["a", "a"], ["a", "a"], ["a", "b"], ["b", "b"], ["b", "c"],
# ["c", "c"], ["c", "a"], ["a", "a"], ["a", "a"], ["a", "a"],
# ["a", "d"], ["d", "d"], ["d", "b"], ["b", "a"],
# ["a", "b"]]

enum1.count(subarr)
#=> enum1.count(["a", "a"])
#=> 5

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);

Count the number of times a particular string appears in a given word

The short and simple pythonic way to do it would be

'asdadgfrdad'.count('dad')

However, your answer may or may not be what you expect when you look at something like 'dadad'.count('dad') which returns 1 instead of 2. This is because str.count returns the number of non-overlapping occurrences of substring. On the other hand, if you want to find the number of overlapping substrings, you'll have to use the following code:

haystack = 'dadad'
needle = 'dad'
sum(haystack[i:i+len(needle)] == needle for i in range(len(haystack)))


Related Topics



Leave a reply



Submit