Using substring()
and indexOf()
makes this really easy
public static void main(String[] args) throws Exception {
String testString = "aabacbba";
System.out.println(findString(testString, 2, "c"));
}
private static int findString(String stringToSearch, int start, String stringToFind) {
int index = stringToSearch.substring(start).indexOf(stringToFind);
// Add start to the result of indexOf to have the actual index in the original string
// It'll return a -1 if no result is found
return index > -1 ? index + start : index;
}
Results:
findString(testString, 2, "a") => returns 3
findString(testString, 2, "c") => returns 4
findString(testString, 2, "d") => returns -1
findString(testString, 1, "bb") => returns 5
UPDATE
After reading a comment about checking to make sure the character is a single occurrence after the start location, I've made an update answer.
public static void main(String[] args) throws Exception {
String testString = "aabacbba";
System.out.println(findString(testString, 3, "b"));
}
private static int findString(String stringToSearch, int start, String stringToFind) {
int index = stringToSearch.substring(start).indexOf(stringToFind);
// Check the next character to make sure it's a single occurrence
if (index > -1 && stringToSearch.charAt(index + start + 1) == stringToFind.charAt(0)) {
index = -1;
}
// Add start to the result of indexOf to have the actual index in the original string
// It'll return a -1 if no result is found
return index > -1 ? index + start : index;
}
Results:
findString(testString, 3, "b") => returns -1, because b repeats
findString(testString, 2, "a") => returns 3
findString(testString, 2, "c") => returns 4