我有字符串

a.b.c.d

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

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


当前回答

public class OccurencesInString { public static void main(String[] args) { String str = "NARENDRA AMILINENI"; HashMap occur = new HashMap(); int count =0; String key = null; for(int i=0;i<str.length()-1;i++){ key = String.valueOf(str.charAt(i)); if(occur.containsKey(key)){ count = (Integer)occur.get(key); occur.put(key,++count); }else{ occur.put(key,1); } } System.out.println(occur); } }

其他回答

我看到过很多这样的花招。现在我不反对漂亮的技巧,但就我个人而言,我喜欢简单地调用那些意味着要做工作的方法,所以我创造了另一个答案。

注意,如果性能有问题,请使用Jon Skeet的答案。在我看来,这个更一般化,因此可读性稍强(当然,对于字符串和模式也可重用)。

public static int countOccurances(char c, String input) {
    return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);
}

public static int countOccurances(String s, String input) {
    return countOccurancesOfPattern(Pattern.quote(s), input);
}

public static int countOccurancesOfPattern(String pattern, String input) {
    Matcher m = Pattern.compile(pattern).matcher(input);
    int count = 0;
    while (m.find()) {
        count++;
    }
    return count;
}
public static int countOccurrences(String container, String content){
    int lastIndex, currIndex = 0, occurrences = 0;
    while(true) {
        lastIndex = container.indexOf(content, currIndex);
        if(lastIndex == -1) {
            break;
        }
        currIndex = lastIndex + content.length();
        occurrences++;
    }
    return occurrences;
}

为什么不只是分割字符,然后得到结果数组的长度。数组长度总是实例数+ 1。对吧?

好吧,在一个非常相似的任务中,我偶然发现了这个线程。 我没有看到任何编程语言的限制,因为groovy运行在java虚拟机上: 这里是我如何能够解决我的问题使用Groovy。

"a.b.c.".count(".")

完成了。

好的,受Yonatan解决方案的启发,这里有一个纯递归的库方法-唯一使用的库方法是length()和charAt(),它们都不做任何循环:

public static int countOccurrences(String haystack, char needle)
{
    return countOccurrences(haystack, needle, 0);
}

private static int countOccurrences(String haystack, char needle, int index)
{
    if (index >= haystack.length())
    {
        return 0;
    }

    int contribution = haystack.charAt(index) == needle ? 1 : 0;
    return contribution + countOccurrences(haystack, needle, index+1);
}

递归是否算作循环取决于您使用的确切定义,但这可能是您能得到的最接近的定义。

我不知道现在大多数jvm是否都做尾递归…当然,如果不是这样,对于适当长的字符串就会出现同名堆栈溢出。