I am trying to get a substring out of a string. I have written logic to provide a start index and an end index but getting below exception. The code is:
final int startIndex = header.indexOf(startValue + ":")
+ (startValue + ":").length();
final int endIndex = header.indexOf(endValue + ":");
return header.substring(startIndex, endIndex).trim();
The exception:
'String index out of range: -4' java.lang.StringIndexOutOfBoundsException: String index out of range: -4 at java.lang.String.substring(String.java:1967)
Any help would be appreciated.
The relevant code of
substringis:If you see
-4in the exception's message, this meansendIndex - beginIndex == -4.Obviously,
endIndexshould be larger than or equal tobeginIndex, so that the difference won't be negative.Looking at the full method (this version of the code seems to match your version, based on the line number - 1967 - in which the exception was thrown):
you can see that you would have gotten
-1in the error message ifbeginIndexwas-1.But if
beginIndexis non-negative, andendIndexis not too large, the number you get in the exception's message isendIndex - beginIndex.