[英]Java - counting letter occurrence in a string using IndexOf
public static void countLetters (String s, char x){
int length = s.length();
int count = 0;
int index = 0;
int z = 0;
while (index < length) {
int y = s.indexOf(x, z);
z = z+1;
if(s.charAt(y)==x){
count = count + 1;
}
index = index + 1;
}
System.out.println(count);
大家好,我是Java的新手,因此非常感谢您提供任何指导。 我正在尝试编写一种方法来计算给定字符串和char中字母的出现。
当前的方法确实可以计数,但并不完全正确。 我被要求使用indexOf方法来解决此问题。 我遇到的问题是,如果我输入一个文本“ amazing”并要求找到字符“ a”,它将首先通过“ a”并计数更新,但是当涉及字符“ m”时,再次计数我不想要的更新它。
我正在使用Allen Downey的一本名为think java的书-练习8.3。 它没有任何作业:)。
这条路
public static void countLetters(String string, char character) {
int count = 0;
int index = 0;
while(true) {
index = string.indexOf(character, index) + 1; // +1 is to continue search
if (index == 0) //from next character after match
break;
count++;
}
System.out.println(count);
}
用countLetters("amazingaa", 'a');
调用countLetters("amazingaa", 'a');
给4
您一次遍历一个字符: z = z+1
,但是当您调用s.indexOf(x, z)
,将返回x
首次出现(大于z
)。 所以您的迭代将如下所示:
因此,您应该执行z = y+1
而不是z = z+1
,并在s.indexOf(x, z)
返回-1时停止迭代。
您应该使用此:
int length = s.length();
int count = 0;
int z = 0;
while (z < length) {
int y = s.indexOf(x, z);
if(y == -1){
break;
}
z = (y == z) ? z + 1 : y + 1;
if (s.charAt(y) == x) {
count = count + 1;
}
}
System.out.print(count);
基本上,当您使用s.indexOf(chr, fromIndex)
它会从指定的索引中检查s.indexOf(chr, fromIndex)
直到找到它为止,这就是为什么当它位于m
时仍会检查直到在字符串中找到a
。 另外,如果找不到该字符串,则应检查为-1
并中断搜索,因为从索引到字符串末尾都找不到该字符串,这将是搜索的结尾。 这样可以防止在检查if(s.charAt(y) == x)
表达式z = (y == z) ? z + 1 : y + 1;
z = (y == z) ? z + 1 : y + 1;
更像是if语句。 ?
是三元运算符,是以下形式的缩写:
if(y == z){
z = z + 1;
}else{
z = y + 1;
}
因为使用else语句设置带有表达式的变量的值很简单,所以可以使用三元运算符保存代码行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.