3 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個贊
您需要遍歷第一個字符串,直到找到另一個字符串的第一個字符。從那里,您可以創(chuàng)建一個內(nèi)部循環(huán)并同時(shí)迭代兩者,就像您所做的那樣。提示:一定要注意邊界,因?yàn)樽址拇笮】赡懿煌?/p>

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個贊
String data = "foo-bar-baz-bar-";
String pattern = "bar";
int foundIndex = data.indexOf(pattern);
while (foundIndex > -1) {
System.out.println("Match found at: " + foundIndex);
foundIndex = data.indexOf(pattern, foundIndex + pattern.length());
}

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個贊
你可以試試這個:-
String a1 = "foo-bar-baz-bar-";
String pattern = "bar";
int foundIndex = 0;
while(foundIndex != -1) {
foundIndex = a1.indexOf(pattern,foundIndex);
if(foundIndex != -1)
{
System.out.println(foundIndex);
foundIndex += 1;
}
}
indexOf- 第一個參數(shù)是模式字符串,
第二個參數(shù)是我們必須搜索的起始索引。
如果找到模式,它將返回模式匹配的起始索引。
如果未找到模式,indexOf將返回 -1。
添加回答
舉報(bào)