我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
不确定这样做的效率,但这是我在不引入第三方库的情况下所能写的最短代码:
public static int numberOf(String target, String content)
{
return (content.split(target).length - 1);
}
其他回答
在代码的某个地方,某些东西必须循环。解决这个问题的唯一方法是完全展开循环:
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”。
这就是我用来计算字符串出现次数的方法。
希望有人觉得有用。
private long countOccurrences(String occurrences, char findChar){
return occurrences.chars().filter( x -> {
return x == findChar;
}).count();
}
我的“惯用的一句话”解决方案:
int count = "a.b.c.d".length() - "a.b.c.d".replace(".", "").length();
不知道为什么使用StringUtils的解决方案是可以接受的。
使用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));
}