我有字符串

a.b.c.d

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

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


当前回答

使用Java 8和HashMap,没有任何库来计数所有不同的字符:

private static void countChars(String string) {
    HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
    string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));
    hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + ":" + i));
}

其他回答

String[] parts = text.split(".");
int occurances = parts.length - 1;

" It's a great day at O.S.G. Dallas! "
     -- Famous Last Words

好吧,这是一个了解Java的情况,特别是对Java中已经可用的集合类的基本理解。如果你看了整篇文章,除了斯蒂芬·霍金对宇宙起源的解释,达尔文关于进化论的平装书,以及吉恩·罗登贝瑞的《星际迷航》演员选择,他们为什么选择威廉·夏特纳,除了如何快速简单地做到这一点……

... 我还需要多说吗?

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

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

如果你使用Spring框架,你也可以使用“StringUtils”类。 方法是“countOccurrencesOf”。

我不喜欢为此目的分配一个新字符串的想法。由于字符串在后面已经有一个char数组,用于存储它的值,string . charat()实际上是免费的。

for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))

只使用J2SE,在1行或更少的时间内,无需需要收集的额外分配。

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

例如,

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

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