如何解决java编程语言中的索引问题
public static int indexOf(String text , char index){
char array [] = new char[text.length()];
for(int i = 0 ; i < text.length(); i++){
array[i] = text.charAt(i);
}// end of first loop
// the above loop converts the string obj to char array
for(int i = 0 ; i < array.length; i++){
if(array[i] == index){ // if a given letter is exist in string
System.out.println("The index of " + index + " is " + i);
return i; // show or return the index of that given letter
}
}//end of second loop
System.out.println("The Letter you Entered does not Exist");
return -1;
}// end of method
这段代码用于查找字符串的索引; 首先,它将一个字符串和一个字符作为输入,然后将其转换为字符数组,然后搜索给定的letter(如果找到)。 方法将返回其索引,但主要问题是字符串中有多个相同的字母,因此它将返回第一个字母。 我如何检测第二个字母,或者如何区分第二个相同的字母,并显示它是索引,例如:
indexOf(“国王小丑”,k')
在kingjoker字符串中,我们有两个k字母,方法无法找到第二个k索引,这就是问题所在
# 1 楼答案
int[]
以下是您修改后的实现: