我找不到有关此异常的答案。程序很简单,但是我不知道为什么不正确。
/**
* Program selects the first word from the sentence "Hello, my dear!" with
* the String Classes's methods this.indexOf() and this.substring()
*
*
* Last modify: 29th October 2015
*/
public class TakeSubstringWanted {
public static void main(String[] args) {
String sentence = "Hello, my dear!";
String reference = "Hello";
System.out.println("The sentence is: " + sentence);
System.out.println("You want to take the first word of that sentence");
System.out.println("Give me a second...");
int firstReference = sentence.indexOf(reference);
int firstLength = reference.length();
System.out.println("The first reference of the searched word is " + firstReference);
System.out.println("The first word of the sentence " + sentence + " is: " + "\"" + sentence.substring(firstReference, firstLength) + "\"");
int secondReference = sentence.indexOf("my");
System.out.println("The second reference of the searched word is " + secondReference);
int secondLength = "my".length();
System.out.println(secondLength);
System.out.println(sentence);
System.out.println("The second word of the sentence " + sentence + " is: " + "\"" + sentence.substring(secondReference, secondLength) + "\"");
}
}
最佳答案
你的问题在最后一行:
System.out.println("The second word of the sentence " + sentence + " is: "
+ "\"" + sentence.substring(secondReference, secondLength) + "\"");
因为您的 secondReference = 7
和 secondLength = 2
,但是如果您查看 documentation对于子字符串
方法:
public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
...
Throws: IndexOutOfBoundsException - if beginIndex or endIndex are negative, if endIndex is greater than length(), or if beginIndex is greater than startIndex
意思是,您要求 substring 返回从索引 7 到索引 2 的字符串,这会导致 IndexOutOfBoundsException
。您可能想要做的是:
sentence.substring(secondReference, secondReference + secondLength)
关于java - 字符串索引越界异常 : string index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409160/