第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字符串中出現(xiàn)的子字符串

字符串中出現(xiàn)的子字符串

慕妹3242003 2019-06-21 13:03:31
字符串中出現(xiàn)的子字符串為什么下面的算法沒有為我停下來?(Str是我正在搜索的字符串,findStr是我試圖查找的字符串)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);
查看完整描述

3 回答

?
largeQ

TA貢獻(xiàn)2039條經(jīng)驗 獲得超8個贊

最后一行是制造問題。lastIndex永遠(yuǎn)不會在-1,所以會有一個無限循環(huán)。這可以通過將最后一行代碼移動到if塊來解決。

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);


查看完整回答
反對 回復(fù) 2019-06-21
?
忽然笑

TA貢獻(xiàn)1806條經(jīng)驗 獲得超5個贊

StringUtils.CountMatch來自阿帕奇公社朗?

String str = "helloslkhellodjladfjhello";String findStr = "hello";System.out.println(StringUtils.countMatches(str, findStr));

產(chǎn)出:

3


查看完整回答
反對 回復(fù) 2019-06-21
?
瀟瀟雨雨

TA貢獻(xiàn)1833條經(jīng)驗 獲得超4個贊

你的lastIndex += findStr.length();被放置在括號之外,導(dǎo)致無限循環(huán)(當(dāng)沒有發(fā)現(xiàn)時,lastIndex總是到findStr.length()).

以下是固定版本:

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);


查看完整回答
反對 回復(fù) 2019-06-21
  • 3 回答
  • 0 關(guān)注
  • 363 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號