简体   繁体   中英

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)

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");
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM