循环的麻烦以计算字符串中给定字符的数量



我必须使用提供的循环来计算字符串第四弦中出现的字符'b'的次数,由于某种原因,它返回了不正确的数字。我相信这与IF条件有关,但我可能会误会。

任何帮助将不胜感激。

字符串:

字符串fourthstring ="棒球的蝙蝠";

它应该返回3。

代码的格式:

char target        ='b';                               
int  length        = fourthString.length( );               
int  count         = 0;                                
int  startNxtSrch  = 0;                                
int  foundAt       = 0;                               
while( ....... ) {
    foundAt = .......;
    if ( ....... ) {
        startNxtSrch = foundAt +1;
        count += 1;
    } else {
        startNxtSrch = length;
    }
}  
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n", 
                   count,
                   target );

我尝试的是返回错误的数字:

int i = 0;
while( i < length ) {
    foundAt = startNxtSrch;
    if ( fourthString.indexOf('b', startNxtSrch) != -1 ) {
        startNxtSrch = foundAt + 1;
        count += 1;
        i++;
    } else {
        startNxtSrch = length;
        i++;
    }
}
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n", 
                   count,
                   target );

这将为您提供正确的字符计数:

char target        = 'b';
int  length        = fourthString.length( );
int  count         = 0;
int  startNxtSrch  = 0;
int  foundAt       = 0;
while(startNxtSrch < length) {
    foundAt = fourthString.indexOf(target,startNxtSrch);
    if (foundAt>=0) {
        startNxtSrch = foundAt + 1;
        count += 1;
    } else {
        startNxtSrch = length;
    }
}
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n",
            count,
            target );

一种更好的方法是通过整个数组并计算您的字符的次数。

String fourthString = "a bat for baseball";
char target = 'b';
count = 0;
for(int i = 0; i < fourthString.length; i++){
    if(fourthString.charAt(i) == traget){
        count++;
    }
}
System.out.println(count);

您可以使用以下代码行:

int count = StringUtils.countMatches("the string you want to search in", "desired string");

为您的示例:

int count = StringUtils.countMatches("a bat for baseball", "b");

您可以在这里找到类似的问题,此答案:https://stackoverflow.com/a/1816989/8434076

编辑

while(startNxtSrch != lenth)
{
   foundAt = indexOf('b', startNxtSrch);
   if (foundAt != -1)
   {
      startNxtSrch = foundAt +1;
      count += 1;
   }  
   else
      startNxtSrch = length;
} 

对我来说,看起来很复杂。

如果我要编写此代码,这是一个更简单的解决方案:

while( i < length ) {
    if (fourthString.contains("b")) {
        fourthString = fourthString.replaceFirst("b", "");
        count++;
    }
    i++;
}
System.out.printf( "%nThere are %d occurrences of '%c' in fourthStr.%n",
                count,
                target );

最新更新