Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

java - String substring index could be the length of string

This is a Java string problem. I use the substring(beginindex) to obtain a substring. Considering String s="hello", the length of this string is 5. However when I use s.substring(5) or s.substring(5,5) the compiler didn't give me an error. The index of the string should be from 0 to length-1. Why it doesn't apply to my case? I think that s.substring(5) should give me an error but it doesn't.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because the endIndex is exclusive, as specified in the documentation.

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.


I think when I use s.substring(5), it should give me error while it didn't

Why would it be?

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Since the beginIndex is not larger than the endIndex (5 in your case), it's perfectly valid. You will just get an empty String.

If you look at the 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  }

Thus s.substring(5); is equivalent to s.substring(5, s.length()); which is s.substring(5,5); in your case.

When you're calling s.substring(5,5);, it returns an empty String since you're calling the constructor(which is private package) with a count value of 0 (count represents the number of characters in the String):

644 String(int offset, int count, char value[]) {
645         this.value = value;
646         this.offset = offset;
647         this.count = count;
648 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...