通过拆分返回java.lang.StringIndexOutOfBoundsException将前两个单词的第一个字符大写的脚本
下面是我遇到错误的摘录:`通过拆分返回java.lang.StringIndexOutOfBoundsException将前两个单词的第一个字符大写的脚本,java,Java,下面是我遇到错误的摘录:` String[] splitbyspace = search.split(" "); if(splitbyspace.length > 2){ String spacesplitted = splitbyspace[0].substring(0, 1).toUpperCase() + splitbyspace[0].substring(1) + " " + splitbyspace[1].substring(0, 1).toUpperCase() +
String[] splitbyspace = search.split(" ");
if(splitbyspace.length > 2){
String spacesplitted = splitbyspace[0].substring(0, 1).toUpperCase() + splitbyspace[0].substring(1) + " " + splitbyspace[1].substring(0, 1).toUpperCase() + splitbyspace[1].substring(1);
searchIdx = content.indexOf(spacesplitted);
if(searchIdx != -1){
String sentence = content.substring(searchIdx+search.length()+1, content.indexOf('.', searchIdx));
sentence = sentence.replace("\"", "");
sentences.add(sentence);
}
}
下面是错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at Untitled2.taste(Untitled2.java:127)
at Untitled2.answer(Untitled2.java:69)
at Untitled2.main(Untitled2.java:29)
在循环指数方面,我做错了什么?字符串search
的内容是:
乔治·布什是
我想要String spacesplited
使其成为
乔治·布什是
但事实并非如此
抛出的异常
java.lang.StringIndexOutOfBoundsException:字符串索引超出范围
位于27,但与上述摘录中代码块的第3行相对应。它是使用字符串spacesplited
的地方。我在一开始就试图用它来运行您的代码
String content = "George Bush is";
int searchIdx;
而且它可以工作(至少行有异常-如果有其他问题,则为秒)。想想看,问题是search
的开头有空格,里面有两个空格,而您的splitbyspace
有一些空字符串。尝试将每个步骤的结果存储在单独的变量中,并在调试中运行它。另外,为了使它真正防错,仔细阅读——它有一些有趣的东西
最后,如果此代码不仅仅用于教育,我建议您使用一些库,其中已经实现了单词大写/句子拆分。请格式化您的代码。你试过调试器吗?在显示的代码的哪一行抛出异常?修复并添加了info@mrsmith42您的
内容是什么
以及searchIdx
在开头是什么0
?将spacesplitted
打印到控制台,看看它是否包含您期望的内容?内容包含“George Bush is”