我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
使用Eclipse集合
int count = Strings.asChars("a.b.c.d").count(c -> c == '.');
如果你有一个以上的字符计数,你可以使用CharBag如下所示:
CharBag bag = Strings.asChars("a.b.c.d").toBag();
int count = bag.occurrencesOf('.');
注意:我是Eclipse Collections的提交者。
其他回答
这就是我用来计算字符串出现次数的方法。
希望有人觉得有用。
private long countOccurrences(String occurrences, char findChar){
return occurrences.chars().filter( x -> {
return x == findChar;
}).count();
}
下面的源代码会给你答案。在用户输入的单词中出现给定字符串的次数:-
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
迟早会有循环发生。对你来说,编写(非常简单的)循环要比使用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;
}
那么你不需要在你的主代码中有循环-但循环必须在那里的某个地方。
int count = (line.length() - line.replace("str", "").length())/"str".length();
String s = "a.b.c.d";
long result = s.chars().filter(ch -> ch == '.').count();