如何找到字符串的倒数第二个字符?

时间:2013-09-24 20:36:51

标签: java string string-length

我正在尝试找到字符串的倒数第二个字符。我尝试使用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

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1     在java.lang.String.charAt(未知来源)     在snippet.hw5.main(hw5.java:30)

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:1)

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

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