簡體   English   中英

如何找到字符串的倒數第二個字符?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM