我必须使用提供的循环来计算字符“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/