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
this piece of code is for finding the index of string ; first it takes a string and a character as an input than it convert it to array of characters than it search for an given lettter if it finds it. method will return it's index but the main problem is that we have more than one same letter in a string so it will return the first one . and how could i detect the second one or how I can differentiate the second same letter and show it is index for example:
indexOf("kingJoker",'k');
here in kingjoker string we have two k letter the method can't find second k index so that is the problem.
int[]
Here is your modified implementation:
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;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加