我想从特定索引开始搜索字符串的子字符串.
假设我有字符串:"PO DAD PO PE DA X PO ZA RA"
我想开始的索引是字符X
,13也是.如果我想正常搜索"ZA",我会做如下操作:
接下来,我想搜索第一个子串'PO'
,但从"X"
索引向后搜索.所以,我会得到4(因为从左边看它接近X
),而不是15.
我该怎么做?
我想从特定索引开始搜索字符串的子字符串.
假设我有字符串:"PO DAD PO PE DA X PO ZA RA"
我想开始的索引是字符X
,13也是.如果我想正常搜索"ZA",我会做如下操作:
接下来,我想搜索第一个子串'PO'
,但从"X"
索引向后搜索.所以,我会得到4(因为从左边看它接近X
),而不是15.
我该怎么做?
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);
}
输出:
7
`usingSubstring()` took 2ms.
代码注释中解释:)