Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to count occurrences of a character or substring

Short answer

For a single character, filter the chars() stream:

void main() {
    long count = "banana".chars().filter(c -> c == 'a').count();
    IO.println(count);
}

Output:

3

A substring

Search for a substring with indexOf() in a loop, moving the start position each time:

int countOf(String text, String part) {
    int count = 0;
    int index = text.indexOf(part);
    while (index != -1) {
        count++;
        index = text.indexOf(part, index + part.length());
    }
    return count;
}
 
void main() {
    IO.println(countOf("the cat and the hat", "the"));
}

Output:

2

Using the string length

A short trick: remove all occurrences and see how much the length went down:

void main() {
    String text = "a,b,c,d";
    int commas = text.length() - text.replace(",", "").length();
 
    IO.println(commas);
}

Output:

3

Frequency of every character

To count every character, collect them into a Map with merge():

void main() {
    var counts = new TreeMap<Character, Integer>();
    for (char c : "hello".toCharArray()) {
        counts.merge(c, 1, Integer::sum);
    }
    IO.println(counts);
}

Output:

{e=1, h=1, l=2, o=1}

Common mistake

Moving the search by 1 instead of the substring length. Then overlapping occurrences are counted several times:

void main() {
    String text = "aaaa";
    int count = 0;
    for (int i = text.indexOf("aa"); i != -1; i = text.indexOf("aa", i + 1)) {
        count++;
    }
    IO.println(count);
}

Output:

3

If you need non-overlapping occurrences, move by part.length() as in the example above — then the result is 2.

Functions used in this recipe

  • String.chars() — Returns a stream of the character codes of a string.
  • String.indexOf() — Finds the position of the first occurrence of a character or a substring.
  • String.replace() — Replaces every occurrence of a substring or a character with another string.
  • String.length() — Returns the number of characters in a string.

Thanks for reading!

Donate to the site — we work hard for you.