Question

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)

Was it helpful?

Solution 2

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
    // ...
}

OTHER TIPS

May be you could try this one:

public void SecondLastChar(){
    String str = "Sample String";
    int length = str.length();
    if (length >= 2)
        System.out.println("Second Last String is : " + str.charAt(length-2));
    else
        System.out.println("Invalid String");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top