在java中使用while循环计算字符串中的实例
问题 在字符串的开头和断点之间有多少个特定字符的实例 断点是另一个角色的第一个实例 例如,我的字符串可以是 hi,我需要help!解决这个问题 我想使用while循环来计算从开始到结束的在java中使用while循环计算字符串中的实例,java,string,while-loop,break,do-while,Java,String,While Loop,Break,Do While,问题 在字符串的开头和断点之间有多少个特定字符的实例 断点是另一个角色的第一个实例 例如,我的字符串可以是 hi,我需要help!解决这个问题 我想使用while循环来计算从开始到结束的hs,因此输出将是2 我对java非常陌生,所以我只知道如何使用while循环来计算某个数字,但我不知道如何中断或如何要求它只计算某个字符。任何正确方向的暗示都会很好 我的想法是这样做: while(character equals 'h', count) else(don't count) break if(c
h
s,因此输出将是2
我对java非常陌生,所以我只知道如何使用while循环来计算某个数字,但我不知道如何中断或如何要求它只计算某个字符。任何正确方向的暗示都会很好
我的想法是这样做:
while(character equals 'h', count)
else(don't count)
break if(character equals !)
print
但我不知道如何将其转换为java
/**
* Method Name: countChars
* Arguments: 4 (Original String, Character to be found, Start Index,
* Stop/Terminate Character)
* Returns: Character Count
**/
public int countChars(String str, char c, int start, char e) {
char[] chr = str.toCharArray();
/* Initialize Count Counter */
int count = 0;
/* Initialize Counter With Start Index */
int i = start;
/* Iterate String For Positive Matches */
while(i < chr.length) {
/* Core Logic */
if(chr[i] == e) {
/* Terminate Character Found : Break Loop */
break;
} else if(chr[i] == c) {
/* Match Found : Increment The Counter */
count++;
}
/* Increment Loop Counter */
++i;
}
/* Return Character Count */
return count;
}
下面是一个快速代码片段:
/**
* Method Name: countChars
* Arguments: 4 (Original String, Character to be found, Start Index,
* Stop/Terminate Character)
* Returns: Character Count
**/
public int countChars(String str, char c, int start, char e) {
char[] chr = str.toCharArray();
/* Initialize Count Counter */
int count = 0;
/* Initialize Counter With Start Index */
int i = start;
/* Iterate String For Positive Matches */
while(i < chr.length) {
/* Core Logic */
if(chr[i] == e) {
/* Terminate Character Found : Break Loop */
break;
} else if(chr[i] == c) {
/* Match Found : Increment The Counter */
count++;
}
/* Increment Loop Counter */
++i;
}
/* Return Character Count */
return count;
}
你的想法听起来不错。试试看。阅读有关while循环、条件和变量的教程。你应该先做家庭作业。这很简单,你的想法听起来不错。试试看。阅读有关while循环、条件和变量的教程。你应该先做家庭作业。这很简单。没有解释的代码转储对初学者没有帮助。请解释一下你在这段代码中所做的事情。另外,我认为这并不完全符合要求——它应该转到“另一个字符”的第一个实例,而不是在某个范围内。@Andy感谢你的回答。添加注释&更改终止条件。循环的注释对我来说很有意义,我以前也做过一些。我在写的这本书特别要求使用while循环,并使用字符串变量,有没有这样做的方法?@Nick94107将它改为使用
while
而不是for
。没有解释的代码转储对初学者没有帮助。请解释一下你在这段代码中所做的事情。另外,我认为这并不完全符合要求——它应该转到“另一个字符”的第一个实例,而不是在某个范围内。@Andy感谢你的回答。添加注释&更改终止条件。循环的注释对我来说很有意义,我以前也做过一些。我正在编写的这本书特别要求使用while循环,并使用字符串变量,有没有这样做的方法?@Nick94107将它改为使用while
而不是for
。