這是一個Java字符串問題。我使用substring(beginindex)
來獲取子字符串。 考慮到String s="hello"
,該字符串的長度是5.但是,當我使用s.substring(5)
或s.substring(5,5)
編譯器沒有給我一個錯誤。字符串的索引應該從0到length-1。 爲什麼它不適用於我的情況?我認爲s.substring(5)
應該給我一個錯誤,但它不會。字符串子字符串索引可能是字符串的長度
回答
因爲endIndex
是排他性的,如documentation中所述。
IndexOutOfBoundsException - 如果將beginIndex爲負,或者endIndex的 比該字符串對象的長度大,或beginIndex 大於endIndex。
當我用s.substring(5)我想,這應該給我的錯誤,而它 沒有
爲什麼它會是什麼?
返回一個新字符串,該字符串是該字符串的子字符串。子字符串 以指定索引處的字符開頭,並擴展到該字符串的 結尾。
由於beginIndex
是(你的情況5)比endIndex
沒有較大的,這是完全有效的。你只會得到一個空字符串。
如果你看一下source code:
1915 public String substring(int beginIndex) {
1916 return substring(beginIndex, count);
1917 }
....
1941 public String substring(int beginIndex, int endIndex) {
1942 if (beginIndex < 0) {
1943 throw new StringIndexOutOfBoundsException(beginIndex);
1944 }
1945 if (endIndex > count) {
1946 throw new StringIndexOutOfBoundsException(endIndex);
1947 }
1948 if (beginIndex > endIndex) {
1949 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1950 }
1951 return ((beginIndex == 0) && (endIndex == count)) ? this :
1952 new String(offset + beginIndex, endIndex - beginIndex, value);
1953 }
因此s.substring(5);
相當於這是你的情況s.substring(5,5);
。
當你調用s.substring(5,5);
,它返回一個空字符串,因爲你調用構造函數(這是私人包)爲0的count
值(count
代表字符的字符串數):
644 String(int offset, int count, char value[]) {
645 this.value = value;
646 this.offset = offset;
647 this.count = count;
648 }
但它沒有索引== 5。但我可以使用s.substring(5)?爲什麼 – user3382017
@ user3382017's.substring(5);'相當於's.substring(5,s.length());'s.substring(5) ,5);'爲「你好」。 –
因爲substring
被定義爲這樣的,你可以在the Javadoc of String.substring
拋出IndexOutOfBoundsException異常發現,如果將beginIndex爲負, 或endIndex是大於此String對象的長度或 beginIndex大於endIndex。
這是非常有用在許多情況下,你總是可以創建一個在一個字符串的字符之後開始一子。
由於endIndex
可以是串的長度,及beginIndex
可以大如endIndex
(但不大於),它也還可以用於beginIndex
爲等於該字符串的長度。
+1。你剛剛教了我一些東西。 minIndex可以等於長度。我從來沒有做過,所以我認爲這是非法的。 – aliteralmind
在第一種情況下(s.substring(5)
)中,Oracle的文檔說
...
IndexOutOfBoundsException - 如果的beginIndex爲負或大於這個字符串對象的長度大。
...
在第二種情況下(s.substring(5,5)
),它說,
...
IndexOutOfBoundsException - 如果的beginIndex爲負,或者endIndex大的長度大此String對象或beginIndex大於endIndex
...
- 1. 從字符串中提取可變長度的子字符串
- 2. 從字符串中間拉取可變長度子字符串
- 3. 字符串的長度比字符串的長度長
- 4. 字符串索引必須是整數 - 子字符串
- 5. hw搜索索引字符串列表中的子字符串?
- 6. Awk--將字符串分成長度爲n的子字符串
- 7. 從任意長度的字符串中提取子字符串
- 8. 查找字符串中所有子字符串的長度
- 9. 在指定長度的子字符串中拆分字符串
- 10. 只有字符串長度大於2的子字符串
- 11. 如何打印出字符串索引字符串中字符串的字符
- 12. 子索引成字符串
- 13. 字符串拆分/字符串替換基於字符長度
- 14. 可變長度TSQL子字符串
- 15. 查找字符串中的所有3個字符長度的子字符串
- 16. SQL子字符串使用charindex - somelength或字符串長度 - somelength
- 17. DBReader提供字符串的長度而不是字符串
- 18. 索引字符串?
- 19. 字符串索引
- 20. 索引字符串
- 21. 的Perl:字符串中子字符串或子字符串中
- 22. 查找字符串中子字符串的所有索引
- 23. Noob,創建字符串方法的索引和子字符串
- 24. C#中的字符串性能 - 什麼是更快地比較,字符串文字或字符串長度
- 25. 如何檢索在字符串中具有可變長度的字符的子字符串?
- 26. 作爲字符的索引字符串
- 27. bash的字符串長度
- 28. 字符串的長度(Python)
- 29. JQ不能索引字符串字符串「值」
- 30. 長字符串
's.substrin g(s.length())'是愚蠢但是有效的 – 2014-03-29 11:17:37
*「我認爲當我使用s.substring(5)時,它應該給我錯誤,而不是」* - 不要依靠你的直覺。閱讀javadocs。他們說不應該。 –