有没有一种简单的方法(而不是手动遍历所有的字符串,或循环遍历indexOf),以便找到一个字符出现在字符串中的次数?
假设我们有"abdsd3 $ asda $ asasdd $ sadas",我们希望$出现3次.
Dan*_*iel 109
public int countChar(String str, char c)
{
int count = 0;
for(int i=0; i < str.length(); i++)
{ if(str.charAt(i) == c)
count++;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
这绝对是最快的方式.这里的正则表达式要慢很多,而且可能更难理解.
Dmi*_*urg 53
功能风格(Java 8,只是为了好玩):
str.chars().filter(num -> num == '$').count()
Run Code Online (Sandbox Code Playgroud)
Mar*_*elo 31
不是最佳的,但计算出现次数的简单方法:
String s = "...";
int counter = s.split("\\$", -1).length - 1;
Run Code Online (Sandbox Code Playgroud)
注意:
the*_*sch 23
你可以使用Apache Commons ' StringUtils.countMatches(String string, String subStringToCount).
既然你正在扫描整个字符串,你可以建立一个完整的字符数并进行任意数量的查找,所有这些都是相同的大成本(n):
public static Map<Character,Integer> getCharFreq(String s) {
Map<Character,Integer> charFreq = new HashMap<Character,Integer>();
if (s != null) {
for (Character c : s.toCharArray()) {
Integer count = charFreq.get(c);
int newCount = (count==null ? 1 : count+1);
charFreq.put(c, newCount);
}
}
return charFreq;
}
// ...
String s = "abdsd3$asda$asasdd$sadas";
Map counts = getCharFreq(s);
counts.get('$'); // => 3
counts.get('a'); // => 7
counts.get('s'); // => 6
Run Code Online (Sandbox Code Playgroud)