Groovy计算字符串中的字符数

x33g5p2x  于2022-10-05 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(446)

这个例子将使用groovy查找一个字符串中一个字符的出现次数。我们将使用字符串计数方法,findAll传递一个闭包,并将字符串转换为char数组,传递ASCII值给计数方法。

计算字符串中的字符数量

@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")
}

查找字符串中的所有字符

如果你不喜欢上面的计数方式,你可以先进行过滤,然后找到所得到的集合的大小。

@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()
}

通过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)
}

相关文章

微信公众号

最新文章

更多