2013-09-24 91 views
-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 

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

+1

请向我们显示您的代码。 –

+1

你想要倒数第二还是最后一个字? – RandomQuestion

+1

请告诉我们你在说什么语言!向我们显示代码,复制确切的错误消息。这太笼统了,无法回答。 –

回答

1

如果您要计算字符串末尾的两个字符,您首先需要确保该字符串至少有两个字符长度,否则您将试图读取负指数字符(即在字符串开始之前):

if (word.length() >= 2)   // if word is at least two characters long 
{ 
    slc = word.length() - 2; // access the second from last character 
    // ... 
} 
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"); 
} 
相关问题