我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
这是一个稍微不同风格的递归解决方案:
public static int countOccurrences(String haystack, char needle)
{
return countOccurrences(haystack, needle, 0);
}
private static int countOccurrences(String haystack, char needle, int accumulator)
{
if (haystack.length() == 0) return accumulator;
return countOccurrences(haystack.substring(1), needle, haystack.charAt(0) == needle ? accumulator + 1 : accumulator);
}
其他回答
迟早会有循环发生。对你来说,编写(非常简单的)循环要比使用split之类的东西简单得多,后者比你需要的功能强大得多。
无论如何要将循环封装在一个单独的方法中,例如。
public static int countOccurrences(String haystack, char needle)
{
int count = 0;
for (int i=0; i < haystack.length(); i++)
{
if (haystack.charAt(i) == needle)
{
count++;
}
}
return count;
}
那么你不需要在你的主代码中有循环-但循环必须在那里的某个地方。
import java.util.Scanner;
class apples {
public static void main(String args[]) {
Scanner bucky = new Scanner(System.in);
String hello = bucky.nextLine();
int charCount = hello.length() - hello.replaceAll("e", "").length();
System.out.println(charCount);
}
}// COUNTS NUMBER OF "e" CHAR´s within any string input
lambda一行代码 不需要外部库。 用每个字符的计数创建一个映射:
Map<Character,Long> counts = "a.b.c.d".codePoints().boxed().collect(
groupingBy( t -> (char)(int)t, counting() ) );
获取:{a=1, b=1, c=1, d=1, .=3} 某一人物的数目。”。’已经结束了: 计数。('。”)
(出于病态的好奇心,我也写了一个lambda解,想知道我的解有多慢,最好是来自有10行解的人。)
下面是一个没有循环的解决方案:
public static int countOccurrences(String haystack, char needle, int i){
return ((i=haystack.indexOf(needle, i)) == -1)?0:1+countOccurrences(haystack, needle, i+1);}
System.out.println("num of dots is "+countOccurrences("a.b.c.d",'.',0));
嗯,有一个循环,但它是看不见的:-)
——约拿单
使用lambda函数删除所有字符进行计数 计数是前长度和后长度之差
String s = "a.b.c.d";
int count = s.length() - deleteChars.apply( s, "." ).length(); // 3
在这里找到deleteChars
如果你需要计算多个字符的出现次数,你可以一次性完成: 如。对于b c和。
int count = s.length() - deleteChars.apply( s, "bc." ).length(); // 5