这个例子将使用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()
}
@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)
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.leveluplunch.com/groovy/examples/count-number-of-occurrences-of-character-in-string/
内容来源于网络,如有侵权,请联系作者删除!