substring() method:
In Java, the substring() method is a part of the String class and is used to extract a portion of a string.
It allows you to retrieve a substring starting from a specified index up to either the end of the string or a specified endpoint.
The general syntax of the substring()
method is:
public String substring(int startIndex)
public String substring(int startIndex, int endIndex)
Here's an explanation of how the substring()
method works:
substring(int startIndex):
This form of the method returns a new string that consists of the characters starting from the startIndex up to the end of the original string.
The startIndex is inclusive, meaning the character at the startIndex will be included in the resulting substring.
The length of the resulting substring will be originalLength - startIndex.
substring(int startIndex, int endIndex):
This form of the method returns a new string that consists of the characters starting from the startIndex up to (but not including) the endIndex.
Both the startIndex and endIndex are inclusive bounds, meaning the characters at these indices are not included in the resulting substring.
The length of the resulting substring will be endIndex - startIndex.
Here are a few examples to illustrate the usage of the substring()
method:
String str = "Hello, World!";
// Get substring from index 7 to the end
String substr1 = str.substring(7);
System.out.println(substr1); // Output: "World!"
// Get substring from index 7 to 12 (exclusive)
String substr2 = str.substring(7, 12);
System.out.println(substr2); // Output: "World"
In the first example, substring(7)
retrieves the substring starting from index 7 ("W") up to the end of the original string, resulting in the substring "World!".
In the second example, substring(7, 12) retrieves the substring starting from index 7 ("W") up to index 12 (exclusive), resulting in the substring "World".
The substring() method is commonly used when you need to extract a portion of a string based on specific starting and ending indices, allowing you to manipulate and work with substrings in Java.
0 Comments