String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
views:
293answers:
4
+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
2010-04-11 02:21:34
lolz, just realised an assignment inside while-loop, then you post an assignment inside for-loop +1
HH
2010-04-11 02:23:38
@polygenelubricants - your "find all occurrences" examples are clever. But if was code-reviewing that, you would get a lecture about code maintainability.
Stephen C
2010-04-11 03:23:42
How would you write it? I'm honestly asking, because I haven't had a professional code review experience before.
polygenelubricants
2010-04-11 03:27:03
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
2010-04-11 02:21:47
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
2010-04-11 02:26:39