Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #82 Count substring occurrences

Find how many times string s contains substring t.
Specify if overlapping occurrences are counted.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
int count = 0;
Pattern pattern = Pattern.compile(String.format("(%s)", t), Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(s);
while(matcher.find()) {
	count++;
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Pattern pattern = Pattern.compile(Pattern.quote(t));
Matcher matcher = pattern.matcher(s);
int count = 0;
while(matcher.find()) count++;
import org.apache.commons.lang3.StringUtils;
int count = StringUtils.countMatches(s, t);
#include <string.h>
unsigned n;
for (n = 0; s = strstr(s, t); ++n, ++s)
	;
(count (re-seq t s))
int SubstringCount(string s, string t, bool allowOverlap = false)
{
  int p = 0;
  int tl = allowOverlap ? 1 : t.Length;
  int cnt = 0;

  while (1 == 1)
  {
    p = s.IndexOf(t, p);
    if (p == -1) break;
    p += tl;
    cnt++;
  }
  return cnt;
}
import std.algorithm;
auto occurrences = s.count(t);
s |> String.split(t) |> Enum.drop(1) |> length()
countOccurence(List1, List2) ->
        countOccurence(List1, List2, 0).

countOccurence(_, [], Count) ->
        Count;
countOccurence(List1, [_ | Rest] = List2, Count) ->
        case (lists:prefix(List1, List2)) of
                true ->
                        countOccurence(List1, Rest, Count + 1);
                false ->
                        countOccurence(List1, Rest, Count)
        end.

countOccurence("ab", "abcddababa").
  lt = len(t) - 1
  k = 1
  num = 0
  do
     print *,s(k:)
     i = index(s(k:),t)
     if (i==0) exit
     num = num + 1
     k = k + i + lt
  end do
  print *,num
import "strings"
x := strings.Count(s, t)
Data.List
length . filter (isPrefixOf t) . tails $ s
sum [ 1 | r <- tails s, isPrefixOf t r ]
let n = 0 // the number of occurences
let acc = s
let i
while ((i = acc.indexOf (t)) + 1) {
  n++
  acc = acc.slice (i + 1)
}
;;; s=str, t=pattern
(defun cnt_substr (str pattern)
  (loop for i from 0 to (- (length str) (length pattern) ) 
    sum (if (equal pattern (subseq str i (+ i (length pattern )))) 1  0 )))
$c = substr_count($s , $t);
uses strutils;
function Count(t, s: String): Integer;
var
  Offset, P: Integer;
begin
  Result := 0;
  Offset := 1;
  P := PosEx(t, s, Offset);
  while P > 0 do
  begin
    Inc(Result);
    P := PosEx(t, s, P + 1);
  end;
end;
my $t="banana bo bana bandana";

my $c =()= $t=~ m/ana/g;
print "count without overlap: $c\n";

$c =()= $t =~ m/an(?=a)/g;
print "count with overlap: $c\n";
count = s.count(t)
s.scan(t).size
let c = s.matches(t).count();

New implementation...
< >
deleplace