我有字符串

a.b.c.d

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

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


当前回答

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;
}

其他回答

使用lambda函数删除所有字符进行计数 计数是前长度和后长度之差

String s = "a.b.c.d";
int count = s.length() - deleteChars.apply( s, "." ).length();  // 3

在这里找到deleteChars

如果你需要计算多个字符的出现次数,你可以一次性完成: 如。对于b c和。

int count = s.length() - deleteChars.apply( s, "bc." ).length();  // 5

一个更简单的解决方案是根据匹配的字符拆分字符串。

例如,

int getOccurences(字符串字符,字符串){ 字符串[]words = String .split(字符); 回来的话。长度- 1; }

这将在以下情况下返回4: getOccurences(“o”,“关于一只敏捷的棕色狐狸的事情”);

你为什么要避开这个循环?我的意思是,如果不检查字符串的每一个字符,你就不能计算“numberOf”点,如果你调用任何函数,它都会以某种方式循环。这是字符串。Replace应该执行一个循环验证字符串是否出现,以便它可以替换每一个出现的字符串。

如果你试图减少资源使用,你不会这样做,因为你创建一个新的字符串只是为了计数点。

现在,如果我们讨论递归的“在这里输入代码”方法,有人说它会因为OutOfMemmoryException而失败,我想他忘记了StackOverflowException。

所以我的方法是这样的(我知道它像其他的,但是,这个问题需要循环):

public static int numberOf(String str,int c) {
    int res=0;
    if(str==null)
        return res;
    for(int i=0;i<str.length();i++)
        if(c==str.charAt(i))
            res++;
    return res;
}

灵感来自Jon Skeet,一个非循环版本,不会吹你的堆栈。如果你想使用fork-join框架,这也是一个有用的起点。

public static int countOccurrences(CharSequeunce haystack, char needle) {
    return countOccurrences(haystack, needle, 0, haystack.length);
}

// Alternatively String.substring/subsequence use to be relatively efficient
//   on most Java library implementations, but isn't any more [2013].
private static int countOccurrences(
    CharSequence haystack, char needle, int start, int end
) {
    if (start == end) {
        return 0;
    } else if (start+1 == end) {
        return haystack.charAt(start) == needle ? 1 : 0;
    } else {
        int mid = (end+start)>>>1; // Watch for integer overflow...
        return
            countOccurrences(haystack, needle, start, mid) +
            countOccurrences(haystack, needle, mid, end);
    }
}

(免责声明:未经测试,未经编译,不合理。)

也许最好的(单线程,不支持代理对)编写方法是:

public static int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (char c : haystack.toCharArray()) {
        if (c == needle) {
           ++count;
        }
    }
    return count;
}
public static void getCharacter(String str){

        int count[]= new int[256];

        for(int i=0;i<str.length(); i++){


            count[str.charAt(i)]++;

        }
        System.out.println("The ascii values are:"+ Arrays.toString(count));

        //Now display wht character is repeated how many times

        for (int i = 0; i < count.length; i++) {
            if (count[i] > 0)
               System.out.println("Number of " + (char) i + ": " + count[i]);
        }


    }
}