5 回答

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
lastIndex = str.indexOf(findStr,lastIndex);
返回 findStr 子字符串在 str 字符串中第一次出現(xiàn)處的 索引 ,從指定的 lastIndex 索引開始。因?yàn)閘astIndex=0;所以第一次查找得到的索引還是0。
應(yīng)該把下面的 lastIndex+=findStr.length();放到while循環(huán)中;這樣不會(huì)死循環(huán)了。

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
lastIndex+=findStr.length(); str.indexof() 檢索到字符串返回字符串的位置 因此str中有次字符串 所以lastIndex永遠(yuǎn)不等于-1
所以是個(gè)死循環(huán)

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個(gè)贊
lastIndex = str.indexOf(findStr,lastIndex); //確定沒有錯(cuò)誤????

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
代碼看起來像這樣。
????String?str?=?"helloslkhellodjladfjhello"; ????String?findStr?=?"hello"; ????int?lastIndex?=?0; ????int?count?=?0; ????while?(lastIndex?!=?-1)?{ ????????lastIndex?=?str.indexOf(findStr,?lastIndex); ????????if?(lastIndex?!=?-1)?{ ????????????count++; ????????????lastIndex?+=?findStr.length(); ????????} ????} ????System.out.println(count);
添加回答
舉報(bào)