tags:

views:

293

answers:

4
String match = "hello";
String text = "0123456789hello0123456789";

int position = getPosition(match, text); // should be 10, is there such a method?
+1  A: 

Use string.indexOf to get the starting index.

Anthony Pegram
+4  A: 
text.indexOf(match);

See the String javadoc

Michael Mrozek
+3  A: 

The family of methods that does this are:

Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].


String text = "0123hello9012hello8901hello7890";
String word = "hello";

System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"

// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; ) {
    System.out.println(i);
} // prints "4", "13", "22"

// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; ) {
    System.out.println(i);
} // prints "22", "13", "4"
polygenelubricants
lolz, just realised an assignment inside while-loop, then you post an assignment inside for-loop +1
HH
@polygenelubricants - your "find all occurrences" examples are clever. But if was code-reviewing that, you would get a lecture about code maintainability.
Stephen C
How would you write it? I'm honestly asking, because I haven't had a professional code review experience before.
polygenelubricants
A: 

You can get all matches in a file simply by assigning inside while-loop, cool:

$ javac MatchTest.java 
$ java MatchTest 
1
16
31
46
$ cat MatchTest.java 
import java.util.*;
import java.io.*;

public class MatchTest {
    public static void main(String[] args){
        String match = "hello";
        String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
        int i =0;
        while((i=(text.indexOf(match,i)+1))>0)
            System.out.println(i);
    }
}
HH
The way you offset `i` by `+1` works, but in a rather roundabout way. As you've shown here, it reports the first `hello` at `i == 1`. It's much more consistent if you always use 0-based indexing.
polygenelubricants
polygenelubricants: kosh, you are right. Have to fix it.
HH
... will steal your thing :P Thank you.
HH