Count number of chars in string

This example will find the number of occurrences of a character in a string using groovy. We will use the string count method, findAll passing a closure and convert the string to a char array passing in the ASCII value to the count method. A comparable example we demonstrate how to count instances of a character in string using java, java 8, guava, apache commons and spring framework.

Count chars in string

@Test
void count_chars_in_string() {

    def lombardiQuote = "The achievements of an organization are " +
            "the results of the combined effort of each individual."

    assert 11, lombardiQuote.count("e")
}

Find all chars in string

If you didn't like the ease of count above, you could filter then find the size of the resulting collection.

@Test
void count_chars_with_filter_string () {

    def lombardiQuote = "Individual commitment to a group effort – that "
        + "is what makes a team work, a company work, a society work, "
        + "a civilization work."

    assert 5, lombardiQuote.findAll({it -> it == "e"}).size()
}

Find chars by ASCII

@Test
void count_chars_in_string_chars () {

    def lombardiQuote = "People who work together will win, whether it be against "
        "complex football defenses, or the problems of modern society."

    assert 7, lombardiQuote.getChars().count(101)
}