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
这段代码用于查找字符串的索引;首先,它采用一个字符串和一个字符作为输入,然后将其转换为字符数组,而不是在找到它时搜索给定的 lettter。方法将返回它的索引,但主要问题是我们在字符串中有多个相同的字母,因此它将返回第一个。以及我如何检测第二个字母或如何区分第二个相同的字母并显示它是索引,例如:
indexOf("kingJoker",'k'(;
在Kingjoker字符串中,我们有两个k字母,该方法找不到第二个k索引,所以这就是问题所在。
- 将方法的返回类型更改为
int[]
- 走一次绳子来计算比赛
- 使数组的大小等于计数
- 再次遍历字符串,边走边填充返回索引。
这是您修改后的实现:
public static int[] indexesOf(String text , char ch) {
int count = 0;
for (int i = 0 ; i != text.length() ; i++) {
if (text.charAt(i) == ch) {
count++;
}
}
int[] indexes = new int[count];
int pos = 0;
for (int i = 0 ; i != text.length() ; i++) {
if (text.charAt(i) == ch) {
System.out.println("Found '" + ch + "' at " + i);
indexes[pos++] = i;
}
}
return indexes;
}
要检测多个字母,我建议您将每个索引存储在一个List<Integer>
中。 您可以使用以下内容(由 smac89 的答案提供(:
public static List<Integer> indexOf(String text, char index) {
return IntStream.range(0, text.length())
.filter(i -> s.charAt(i) == index)
.boxed()
.collect(Collectors.toList());
}