计算字符串中字符出现的简单方法

是否有一种简单的方法(而不是手动遍历所有字符串,或遍历indexOf)以查找字符出现在字符串中的次数?

假设我们有“ abdsd3 $ asda $ asasdd $ sadas”,我们希望$出现3次。


慕森卡
浏览 343回答 3
3回答

拉风的咖菲猫

public int countChar(String str, char c){&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for(int i=0; i < str.length(); i++)&nbsp; &nbsp; {&nbsp; &nbsp; if(str.charAt(i) == c)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; }&nbsp; &nbsp; return count;}这绝对是最快的方法。正则表达式在这里要慢得多,并且可能很难理解。

繁星淼淼

不是最佳方法,而是简单的计数发生次数的方法:String s = "...";int counter = s.split("\\$", -1).length - 1;注意:美元符号是特殊的正则表达式符号,因此必须以反斜杠转义。反斜杠是转义字符(例如换行符)的特殊符号,因此必须使用反斜杠对其进行转义。split的第二个参数可防止删除空的尾随字符串。

慕森王

由于无论如何都要扫描整个字符串,因此您可以建立完整的字符计数并进行任意数量的查找,而所有操作均以相同的高成本(n)进行:public static Map<Character,Integer> getCharFreq(String s) {&nbsp; Map<Character,Integer> charFreq = new HashMap<Character,Integer>();&nbsp; if (s != null) {&nbsp; &nbsp; for (Character c : s.toCharArray()) {&nbsp; &nbsp; &nbsp; Integer count = charFreq.get(c);&nbsp; &nbsp; &nbsp; int newCount = (count==null ? 1 : count+1);&nbsp; &nbsp; &nbsp; charFreq.put(c, newCount);&nbsp; &nbsp; }&nbsp; }&nbsp; return charFreq;}// ...String s = "abdsd3$asda$asasdd$sadas";Map counts = getCharFreq(s);counts.get('$'); // => 3counts.get('a'); // => 7counts.get('s'); // => 6
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java