[英]How do I find the second to last character of a string?
我正在尝试查找字符串的倒数第二个字符。 我尝试使用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:字符串索引超出范围:snippet.hw5.main(hw5.java:30)处的java.lang.String.charAt(Unknown Source)-1
也许您可以尝试以下一种方法:
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 (word.length() >= 2) // if word is at least two characters long
{
slc = word.length() - 2; // access the second from last character
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.