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

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

我必须使用提供的循环来计算字符“b”在字符串 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 );

最佳答案

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

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

关于java - 循环计算字符串中给定字符数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47460511/

相关文章:

java - Spring 启动: Perform encryption/decryption using Annotation: MongoDB

java - 如何使用 pom.xml 将参数传递给 Maven 构建?

c++ - 二维循环 OpenCl 程序不工作

C++如何循环这个东西(初学者)

java - SpringBoot Postgresql 驱动问题

java - 如何获得正确的 JTable 宽度?

C++:在循环内部或外部声明一个 vector

JavaScript 测试 number 变量是否为数字

python - Django 查询结果与if语句比较

android - 使用 if 语句使 EditText 不可编辑