以下是我遇到错误的摘录:`
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
的内容是:
george bush is
我希望String spacesplitted
进入
George Bush is
。
但那并没有发生。
抛出的异常java.lang.StringIndexOutOfBoundsException: String index out of range
位于27,但对应于上述摘录中代码块中的第3行。这是使用String spacesplitted
的地方。
答案 0 :(得分:1)
我尝试在开始时使用此代码运行您的代码
String content = "George Bush is";
int searchIdx;
并且它有效(至少是异常行 - 如果有另一个问题,则为第二行)。想想,问题是search
在开头有空格或者在里面有双空格,而你的splitbyspace
有一些空字符串。尝试将每个步骤的结果存储在单独的变量中,并在调试中运行它。另外,为了使其真正防错,请仔细阅读String#split javadoc - 它有一些有趣的东西。
最后,如果这段代码不只是用于教育,我建议您使用一些库,其中已经实现了大写/分割为句子的单词。