我有字符串

a.b.c.d

我想数一下'的出现次数。,最好是一句单句俏皮话。

(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。


当前回答

一个更简单的解决方案是根据匹配的字符拆分字符串。

例如,

int getOccurences(字符串字符,字符串){ 字符串[]words = String .split(字符); 回来的话。长度- 1; }

这将在以下情况下返回4: getOccurences(“o”,“关于一只敏捷的棕色狐狸的事情”);

其他回答

得到答案最简单的方法如下:

public static void main(String[] args) {
    String string = "a.b.c.d";
    String []splitArray = string.split("\\.",-1);
    System.out.println("No of . chars is : " + (splitArray.length-1));
}

我的“惯用的一句话”解决方案:

int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();

不知道为什么使用StringUtils的解决方案是可以接受的。

在代码的某个地方,某些东西必须循环。解决这个问题的唯一方法是完全展开循环:

int numDots = 0;
if (s.charAt(0) == '.') {
    numDots++;
}

if (s.charAt(1) == '.') {
    numDots++;
}


if (s.charAt(2) == '.') {
    numDots++;
}

...等等,但你是在源代码编辑器中手动执行循环的人——而不是运行它的计算机。请看伪代码:

create a project
position = 0
while (not end of string) {
    write check for character at position "position" (see above)
}
write code to output variable "numDots"
compile program
hand in homework
do not think of the loop that your "if"s may have been optimized and compiled to

我对此的“惯用语”是:

int count = StringUtils.countMatches("a.b.c.d", ".");

既然已经是通用语言了,为什么还要自己写呢?

Spring Framework的线性程序是:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
int count = (line.length() - line.replace("str", "").length())/"str".length();