[英]java substring not working as expected
我正在嘗試在Java中使用子字符串函數,但是它一直拋出錯誤,我想知道為什么? 從邏輯上講,該代碼似乎很好,但是為什么會引發此錯誤
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
我在文檔子字符串中閱讀的內容帶有2個參數
substring(whereIwantToStart,howManyCharactersToshow)
下面是我的代碼
String test = "160994";
System.out.println(test.substring(2,1)); //output should be 09 why error?
有人可以解釋我哪里錯了嗎? 請我解釋一下。 謝謝 :)
參見文檔 :
公共字符串子字符串(int beginIndex,int endIndex)
返回一個新字符串,該字符串是該字符串的子字符串。 子字符串從指定的beginIndex開始,並擴展到索引endIndex-1處的字符。因此,子字符串的長度為endIndex-beginIndex。
您需要"160994".substring(2, 4)
來獲取09
。
對於您所需的輸出,請使用-
System.out.println(test.substring(2,4));
這是Java中子字符串的格式
public String substring(int beginIndex, int endIndex)
您指定從索引2開始到索引1結束,這就是為什么它將異常索引拋出范圍之外的原因。
要獲得09的輸出,您需要
System.out.println(test.substring(2,4));
附錄-Java文檔https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
結束索引應大於開始索引。 要獲得輸出為'09',您應該提供結束索引為4 test.substring(2,4);
返回一個新字符串,該字符串是該字符串的子字符串。 該
子字符串從指定的beginIndex
開始,並擴展到索引endIndex - 1
處的字符。因此,子字符串的長度為
endIndex-beginIndex
。
在以下情況下,將拋出StringIndexOutOfBoundsException
public String substring(int startIndex, int endIndex)
:此方法返回新的String對象,其中包含給定字符串從指定的startIndex到endIndex的子字符串。
讓我們通過下面給出的代碼了解startIndex和endIndex。
String s="hello";
System.out.println(s.substring(0,2));
輸出: he
注意 :
endIndex> startIndex
在您的情況下:在1到2之間更改
String test = "160994";
System.out.println(test.substring(2, 4)); //output should be 09
輸出: 09
字符串測試=“ 160994”;
的System.out.println(test.substring(2,1));
子字符串的意思是(beginIndex,endIndex)和endIndex應該大於beginIndex。並且您的value(09)應該保持在beninIndex(這是起始索引)和endIndex(這是最后一個索引)之間。
並且您采用了endIndex 1,因此由於您的beginIndex大於endIndex而出現錯誤。
如果你想得到Ans。 09,則您必須放置endIndex 4。
行將是:-System.out.println(test.substring(2,4));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.