我有字符串

a.b.c.d

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

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


当前回答

虽然方法可以隐藏它,但没有循环(或递归)就无法计数。但出于性能考虑,您希望使用char[]。

public static int count( final String s, final char c ) {
  final char[] chars = s.toCharArray();
  int count = 0;
  for(int i=0; i<chars.length; i++) {
    if (chars[i] == c) {
      count++;
    }
  }
  return count;
}

使用replaceAll(即RE)听起来不是最好的方法。

其他回答

这个怎么样。它没有在底层使用regexp,因此应该比其他一些解决方案更快,并且不会使用循环。

int count = line.length() - line.replace(".", "").length();
int count = (line.length() - line.replace("str", "").length())/"str".length();

你为什么要避开这个循环?我的意思是,如果不检查字符串的每一个字符,你就不能计算“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;
}
import java.util.Scanner;

class apples {

    public static void main(String args[]) {    
        Scanner bucky = new Scanner(System.in);
        String hello = bucky.nextLine();
        int charCount = hello.length() - hello.replaceAll("e", "").length();
        System.out.println(charCount);
    }
}//      COUNTS NUMBER OF "e" CHAR´s within any string input

试试这个方法:

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