Java 字符串索引超出范围:-1。
我编写了一个方法,它将Java 字符串索引超出范围:-1。,java,substring,indexoutofboundsexception,indexoutofrangeexception,Java,Substring,Indexoutofboundsexception,Indexoutofrangeexception,我编写了一个方法,它将html代码存储为字符串,并将html代码中的图像与我选择的图像交换。我经常得到一个字符串索引超出范围:-1异常。我不明白我在哪里会越界。有人能看看我的代码并给我一个提示吗 public static String replaceImgs(String htmlCode){ String finalString = ""; String toFind = "img src=\""; String imgReplace = "img src=\
html
代码存储为字符串,并将html
代码中的图像与我选择的图像交换。我经常得到一个字符串索引超出范围:-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;
}
如果找不到String.indexOf()方法,则返回-1,并且在代码中忽略它。可能是你现在的问题
顺便说一句,请注意方法String.substring(begin,end)返回一个从开始索引(包括)到结束索引(排除)的字符串。如果没有出现,find
indexOf
将返回-1
与中一样,
-1
应该会给您一个提示。如果没有找到匹配项,indexOf
将返回什么?您知道如何调试代码吗?