我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
我有字符串
a.b.c.d
我想数一下'的出现次数。,最好是一句单句俏皮话。
(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。
当前回答
我不喜欢为此目的分配一个新字符串的想法。由于字符串在后面已经有一个char数组,用于存储它的值,string . charat()实际上是免费的。
for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))
只使用J2SE,在1行或更少的时间内,无需需要收集的额外分配。
其他回答
虽然方法可以隐藏它,但没有循环(或递归)就无法计数。但出于性能考虑,您希望使用char[]。
public static int count( final String s, final char c ) {
final char[] chars = s.toCharArray();
int count = 0;
for(int i=0; i<chars.length; i++) {
if (chars[i] == c) {
count++;
}
}
return count;
}
使用replaceAll(即RE)听起来不是最好的方法。
这是一个稍微不同风格的递归解决方案:
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);
}
这就是我用来计算字符串出现次数的方法。
希望有人觉得有用。
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);
}
}
}
一个简短的例子是
String text = "a.b.c.d";
int count = text.split("\\.",-1).length-1;