Search code examples
javastringstring-length

How do I find the second to last character of a string?


I'm trying to find the second to last character of a string. I try using word.length() -2 but I receive an error. I'm using java

String Word;
char c;

lc = word.length()-1;
slc = word.length()-2; // this is where I get an error.
System.out.println(lc);
System.out.println(slc);//error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.charAt(Unknown Source) at snippet.hw5.main(hw5.java:30)


Solution

  • If you're going to count back two characters from the end of a string you first need to make sure that the string is at least two characters long, otherwise you'll be attempting to read characters at negative indices (i.e. before the start of the string):

    if (word.length() >= 2)         // if word is at least two characters long
    {
        slc = word.length() - 2;    // access the second from last character
        // ...
    }