簡體   English   中英

讀取最后一個字符時,java substring和charAt分別返回“”和異常

[英]java substring and charAt returns “” and exception respectivly while readng the last character

public class StringDemo{

   public static void main(String[] args) {

       String str = "this:";
       int a = str.indexOf(":"); // returns 4
       String subStr = str.substring(a+1); // returns "" <empty string>
       String subStr = str.substring(a+2); // throws exception
      int charAt = str.charAt(a+1); // Throws an StringIndexOutOfBoundsExp.
    }
}

任何人都可以解釋為什么它會返回“”以及為什么它會引發異常

str.substring(a+1)

返回給定索引( a+1之后的字符串該索引是冒號后面的字符串,即空字符串。

str.charAt(a+1)

訪問冒號不存在的位置的數組值。

str.substring(a+1)str STARTING返回a+15的子字符串。 您的字符串在索引5處沒有任何內容,因此它將返回一個空字符串。

不,它不會拋出IndexOutOfBoundException而是返回空String 在第二種方法的情況下, beginIndexendIndex相等的情況也是如此。 beginIndex為負數,大於endIndex或大於length of String它只會拋出StringIndexBoundException

String subStr = str.substring(a + 1); //返回“”。 //因為那個地方什么都沒有

它顯然存在於API中

“emptiness”.substring(9)返回“”(空字符串)

閱讀更多: http//javarevisited.blogspot.com/2011/10/how-substring-in-java-works.html#ixzz2SVu5lyYo

其中CharAt拋出拋出: IndexOutOfBoundsException - 如果index參數為負或不小length of this stringlength of this string

我想首先回答為什么結果是空字符串。

Method:substring(int beginIndex)

就像說

substring(beginIndex,String.length());

在你的參數上指定的endIndex是5,長度也是5.因此,如果你做substring(0,0)或substring(1,1)或substring(5,5),它將始終給出一個空字符串,因為begin和結束指數是平等的。 用簡單的語言來說,相同的開始和結束索引不占用任何因此導致空字符串。

為什么整數5仍然是有效索引? 答案取決於Java API本身:拋出:IndexOutOfBoundsException - 如果beginIndex為負或大於此String對象的長度。

參考:

Java API
String substring()方法示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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