[英]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+1
或5
的子字符串。 您的字符串在索引5
處沒有任何內容,因此它將返回一個空字符串。
不,它不會拋出IndexOutOfBoundException
而是返回空String 。 在第二種方法的情況下, beginIndex
和endIndex
相等的情況也是如此。 當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 string
的length 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對象的長度。
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.