After you've found the first index, use the overloaded version of indexOf that receives the start index as a second parameter:
public int indexOf(int ch, int fromIndex)Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
Keep doing that until indexOf returns -1, indicating that there are no more matches to be found.
You can use regex with Pattern and Matcher. Matcher.find() tries to find the next match and Matcher.start() will give you the start index of the match.
Pattern p = Pattern.compile("create");
Matcher m = p.matcher("I would like to create a book reader have create, create ");
while(m.find()) {
System.out.println(m.start());
}
You can get away without the index variable as you're reassigning it at each step of your loop anyway.
public static int subStringIndex(String str, String substr) {
int substrlen = substr.length();
int strlen = str.length();
int j = 0;
if (substrlen >= 1) {
for (int i = 0; i < strlen; i++) { // iterate through main string
if (str.charAt(i) == substr.charAt(j)) { // check substring
j++; // iterate
if (j == substrlen) { // when to stop
return i - substrlen; //found substring. As i is currently at the end of our substr so sub substrlen
}
}
else {
j = 0;
}
}
}
return -1;
}
Just checking that you intend to be reinventing-the-wheel, you can do:
System.out.println("happy".indexOf("app"));
You did know that, right?
Or, if you want to reformat the 'signature' to match yours, it is:
public static int subStringIndex(String str, String substr) {
return str.indexOf(substr);
}
There are a number of helper methods on String which will help:
- String.indexOf(substr) - return the index of the first occurrence of substr
- String.indexOf(substr, start) - return the index of the first occurrence of substr on or after the start position.
- String.lastIndexOf(substr) - return the index of the last occurrence of substr
- String.lastIndexOf(substr, start) - return the index of the last occurrence of substr starting before the start position. -