-5

我寫了需要存儲爲一個字符串html代碼,並在此html代碼我選擇的圖像交換圖像的方法。我經常會遇到String index out of range: -1異常。我不明白我可以走出界限。有人看我的代碼,並給我一個提示?字符串索引超出範圍:-1。

public static String replaceImgs(String htmlCode){ 
    String finalString = ""; 
    String toFind = "img src=\""; 
    String imgReplace = "img src=\"http://media4.popsugar-assets.com/files/2014/08/08/878/n/1922507/caef16ec354ca23b_thumb_temp_cover_file32304521407524949.xxxlarge/i/Funny-Cat-GIFs.jpg"; 
    String tagReplace = "\">"; 
    String rest = ""; 

    int index = htmlCode.indexOf(toFind); 
    String firstString = htmlCode.substring(0, index); 

    rest = htmlCode.substring(index+1, htmlCode.length()); 
    index = rest.indexOf(tagReplace); 

    String secondString = rest.substring(index, rest.length()); 
    finalString = firstString.concat(imgReplace).concat(secondString); 
    return finalString; 
}  
+11

的'-1'應該給你一個提示。如果找不到匹配項,'indexOf'返回什麼? – Tunaki

+2

你知道如何調試你的代碼嗎? –

回答

1

String.indexOf()方法返回-1,如果未找到並且您在代碼中忽略它。也許是你目前的問題

順便說一句,請注意方法String.substring(開始,結束)返回出發,開始索引(包括)到結束索引(不包括)的字符串。

0

如果沒有occurence是找到indexOf將返回-1

正如JavaDoc

相關問題