循环计算字符串中给定字符数的问题

时间:2017-11-23 17:07:13

标签: java loops if-statement while-loop conditional

我必须使用提供的循环来计算字符'b'出现在String fourthString中的次数,并且由于某种原因它返回的数字不正确。我认为这与if条件有关,但我可能会弄错。

任何帮助都会非常感激。

字符串:

String 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 );

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

您可以使用以下代码行:

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

答案 2 :(得分:0)

更好的方法是通过整个数组并计算你的char出现的次数。

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

答案 3 :(得分:0)

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

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

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