Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I am trying to create my own version of indexOf method, even though it is in the java.lang package.
This is what I have done so far and it does not work, always returns 0 instead of the correct index. Your help is appreciated.public class Indexof {
static String s = "ffdfsfdog";
public static void main(String[] args){if (IndexOf("dog") >= 0){
System.out.println("Your string was found at index " + IndexOf("dog"));
}
else System.out.println("No match found!");
} // end of main methodpublic static int IndexOf(String search){
int place = 0, indexat = 0;
for (int i = 0; i < s.length(); i++){
while (indexat < s.length()){
indexat += i + search.length();
if ( search.equals( s.substring( (0+i), (search.length()+i) ))){ /*compares the strings*/
place = i;
}
}
}
return place;
} // end of IndexOf method
} // end of class

int place = 0, indexat = 0;
for (int i = 0; i < s.length(); i++){
while (indexat < s.length()){
indexat += i + search.length();My guess is that you aren't reseting indexat For the record though, I don't see the need for the second while loop.

That's a good observation, I will change that. I put the while loop so that it does not compare the string out of bounds. Do you agree?

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |