public int countChars(String toSearch,Char c){
  short count=0;
  for(int i=0;i<toSearch.length();i++)
    if (c==toSearch.charAt(i) count++;
  return count;
}public int countChars(String toSearch,Char c){
  int count=0,i=0;
  while((i=toSearch.indexOf(c,i))!=-1)
    count++;
  return count;
}个人觉得相对而言,用for的效率要高一些

解决方案 »

  1.   

    抱歉,犯错误了,呵呵
    if (c==toSearch.charAt(i) count++;
    少了个括号,应该为
    if (c==toSearch.charAt(i))count++;使用while的应该这么写才对
    public int countChars(String toSearch,Char c){
      int count=0,i=-1;
      while((i=toSearch.indexOf(c,i+1))!=-1)
        count++;
      return count;
    }
      

  2.   

    用过tokenize没?没用过建议看看,对分字符串和单词很实用。
      

  3.   

    这个:String str = "a~b~c~d~e~f~g~h~i~j~k";
    int len = str.length();
    int count = 0;
    for (int i=0;i<len;i++){
        if str.charAt(i) == '~' count++;
    }