Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a character from a string

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?

like image 281
Fcoder Avatar asked May 31 '26 05:05

Fcoder


1 Answers

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);
like image 52
Jon Skeet Avatar answered Jun 01 '26 18:06

Jon Skeet