Substring () method of string class

Time:2021-12-6

Intercepting string, usage in Java language

1. substring(int beginIndex)

Returns a new string, which is a substring of this string. The substring starts with the character at the specified index and continues to the end of the string.

Parameter: beginindex – index at the beginning(include),

Return: specified substring

Exception: if beginindex is negative or greater than the length of this string object, an indexoutofboundsexception will be thrown

For example:

“unhappy”.substring(2)  


returns”happy

“mybaby”.substring(3)  


returns”aby

2. substring(int beginIndex, int endIndex)

Returns a new string, which is a substring of this string. The substring starts at the specified beginindex and ends at the specified endindex-1.

Parameters: beginindex – index at the beginning (including).

Index at the end of endindex (excluding).

Returns: the specified substring.

Throw: if beginindex is negative or the length is greater than the string length, an indexoutofboundsexception will be thrown

For example:

“hamburger”.substring(3,8) 


returns “burge

“smiles”.substring(0,5)


returns “smile

This work adoptsCC agreement, reprint must indicate the author and the link to this article