I have this string:
String code="abc";
i want to extract "c" from this string by substring method but it doesn't work:
String code="abc";
String getsmscode=code.substring(2,1);
This code return an error
java.lang.StringIndexOutOfBoundsException: length=3; regionStart=2; regionLength=-1
but i don't know why?
You need to read the documentation for substring - the second parameter isn't a length, it's the end index (exclusive).
Parameters:
beginIndex- the beginning index, inclusive.
endIndex- the ending index, exclusive.
When in doubt, read the docs...
Also note that if you're just trying to get the final character, you can just use the single-parameter overload, which returns a substring from a given start point to the end of the string:
String lastCharacter = text.substring(text.length() - 1);
Or you could get it as a single character:
char lastCharacter = text.charAt(text.length() - 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With