Computing.Net > Forums > Programming > Creating method indexOf - Java

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Creating method indexOf - Java

Reply to Message Icon

Name: Dado
Date: February 22, 2005 at 09:30:40 Pacific
OS: WinXP
CPU/Ram: 1GB
Comment:

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 method

public 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




Sponsored Link
Ads by Google

Response Number 1
Name: mossman2
Date: February 22, 2005 at 11:34:40 Pacific
Reply:

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.


0

Response Number 2
Name: Dado
Date: February 22, 2005 at 14:20:48 Pacific
Reply:

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?


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

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


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Creating method indexOf - Java

implementation of java methods in C www.computing.net/answers/programming/implementation-of-java-methods-in-c/17528.html

Inheritance in Java Objects www.computing.net/answers/programming/inheritance-in-java-objects/1751.html

Random Numbers in Java www.computing.net/answers/programming/random-numbers-in-java/8564.html