我有字符串

a.b.c.d

我想数一下'的出现次数。,最好是一句单句俏皮话。

(之前我把这个约束表述为“不使用循环”,以防你想知道为什么每个人都试图在不使用循环的情况下回答)。


当前回答

我不喜欢为此目的分配一个新字符串的想法。由于字符串在后面已经有一个char数组,用于存储它的值,string . charat()实际上是免费的。

for(int i=0;i<s.length();num+=(s.charAt(i++)==delim?1:0))

只使用J2SE,在1行或更少的时间内,无需需要收集的额外分配。

其他回答

这是一个稍微不同风格的递归解决方案:

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);
}
String s = "a.b.c.d";
long result = s.chars().filter(ch -> ch == '.').count();

这就是我用来计算字符串出现次数的方法。

希望有人觉得有用。

    private long countOccurrences(String occurrences, char findChar){
        return  occurrences.chars().filter( x -> {
            return x == findChar;
        }).count();
    }
 public static String encodeMap(String plainText){
        
        Map<Character,Integer> mapResult=new LinkedHashMap<Character,Integer>();
        String result = "";
        for(int i=0;i<plainText.length();i++){
            if(mapResult.containsKey(plainText.charAt(i))){
            Integer v =mapResult.get(plainText.charAt(i));
            mapResult.put(plainText.charAt(i), v+1);
            }else{
                mapResult.put(plainText.charAt(i), 1);
            }
        }
        
        for(Map.Entry<Character, Integer> t : mapResult.entrySet()) {
            result += String.valueOf(t.getKey())+t.getValue();
        }
        
        return result;
        
    }

 public static void main(String args[]) {
        String  plainText = "aaavvfff";
        System.out.println(encodeMap(plainText)); //a3v2f3  
    }

试试这个方法:

StringTokenizer stOR = new StringTokenizer(someExpression, "||");
int orCount = stOR.countTokens()-1;