Why is “out of range” not thrown for 'substring(startIndex, endIndex)'

后端 未结 6 994
生来不讨喜
生来不讨喜 2020-11-27 08:02

In Java I am using the substring() method and I\'m not sure why it is not throwing an \"out of index\" error.

The string abcde has index st

6条回答
  •  攒了一身酷
    2020-11-27 08:30

    From String API javadoc:

    public String substring(int beginIndex)
        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.
    
    public String substring(int beginIndex, int endIndex)
        Returns a new string that is a substring of this 
        string. The substring begins at the specified beginIndex 
        and extends to the character at index endIndex - 1. Thus 
        the length of the substring is endIndex-beginIndex.
    

    Examples:

    "unhappy".substring(2) returns "happy" 
    "Harbison".substring(3) returns "bison"
    "emptiness".substring(9) returns "" (an empty string)
    
    "hamburger".substring(4, 8) returns "urge"
    "smiles".substring(1, 5) returns "mile"
    

    Parameters:

    beginIndex - the beginning index, inclusive.
    Returns:
    the specified substring.
    Throws:
    IndexOutOfBoundsException - if beginIndex is negative or 
    larger than the length of this String object.
    

    ====

    So this is by design. If you give the index as the size of the string, it returns empty string.

提交回复
热议问题