I would like to search for substring of string starting from specific index.
Let’s say I have string: "PO DAD PO PE DA X PO ZA RA"
Index from which I want to start is character X, so is 13. If I would like to search normally for ‘ZA’ I would do something like:
"DAD PO PE DA X PO ZA RA ZA".indexOf("ZA") and I would get 18.
Next I want to search for first substring 'PO' but backward from "X" index. So, I would get 4 (as it is closer to X from left side) not 15.
How could I do this?
Advertisement
Answer
public static void main(String[] args) {
String s = "PO DAD PO PE DA X PO ZA RA";
System.out.println(usingSubstring(s));
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
usingSubstring(s);
}
long end = System.currentTimeMillis();
System.out.println("`usingSubstring()` took " + (end - start) + "ms.");
}
/**
* 1. Get the first index of `X`.
* 2. Substring from 0 ... (1).
* 3. Get the last index from (2) for `PO`.
*
* @param s input string
* @return last index of `PO` backwards from `X`
*/
private static int usingSubstring(String s) {
String toSearch = "PO";
String searchUntil = "X";
return s.substring(0, s.indexOf(searchUntil)).lastIndexOf(toSearch);
}
Outputs:
7 `usingSubstring()` took 2ms.
Explained in code comments 🙂