-1

我正在尝试查找字符串的倒数第二个字符。我尝试使用word.length() -2,但收到错误消息。我正在使用 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

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:-1 at java.lang.String.charAt(Unknown Source) at snippet.hw5.main(hw5.java:30)

4

2 回答 2

2

也许你可以试试这个:

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");
}
于 2016-06-17T12:20:10.267 回答
1

如果您要从字符串末尾倒数两个字符,您首先需要确保字符串至少有两个字符长,否则您将尝试读取负索引处的字符(即在开始之前字符串):

if (word.length() >= 2)         // if word is at least two characters long
{
    slc = word.length() - 2;    // access the second from last character
    // ...
}
于 2013-09-24T21:12:18.793 回答