Java 如何找到字符串的倒数第二个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18991559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the second to last character of a string?
提问by Cooper Taylor
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
我试图找到字符串的倒数第二个字符。我尝试使用,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
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)
线程“main”中的异常 java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.charAt(Unknown Source) at snippet.hw5.main(hw5.java:30)
采纳答案by Paul R
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
// ...
}
回答by bpathak
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");
}