我有字符串

a.b.c.d

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

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


当前回答

完整的示例:

public class CharacterCounter
{

  public static int countOccurrences(String find, String string)
  {
    int count = 0;
    int indexOf = 0;

    while (indexOf > -1)
    {
      indexOf = string.indexOf(find, indexOf + 1);
      if (indexOf > -1)
        count++;
    }

    return count;
  }
}

电话:

int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
System.out.println(occurrences); // 3

其他回答

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

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

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

在java-8中,你也可以使用流来实现这一点。显然,在幕后有一个迭代,但您不必显式地编写它!

public static long countOccurences(String s, char c){
    return s.chars().filter(ch -> ch == c).count();
}

countOccurences("a.b.c.d", '.'); //3
countOccurences("hello world", 'l'); //3
int count = (line.length() - line.replace("str", "").length())/"str".length();

不确定这样做的效率,但这是我在不引入第三方库的情况下所能写的最短代码:

public static int numberOf(String target, String content)
{
    return (content.split(target).length - 1);
}
 public static int countSubstring(String subStr, String str) {

    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.substring(i).startsWith(subStr)) {
            count++;
        }
    }
    return count;
}