Use the substring() method of the StringBuffer class to obtain a substring
In Java programming, the StringBuffer class is widely used to process strings. It provides various methods to manipulate and obtain substrings in strings. Among them, the substring() method is a commonly used method, used to obtain the substring of the specified position range.
The substring() method of the StringBuffer class has two overloaded forms, one is to specify the starting index, and the other is to specify both the starting index and the ending index. Below are usage examples of both forms.
Code example:
StringBuffer sb = new StringBuffer("Hello World"); String subStr = sb.substring(6); System.out.println(subStr);
Output result:
World
Explanation: In the above example, the string "Hello World" is assigned to an instance of the StringBuffer class sb. By calling the substring(6) method of sb, startIndex is set to 6, specifying that the substring should be extracted starting from index 6. Therefore, the output is "World".
Code example:
StringBuffer sb = new StringBuffer("Hello World"); String subStr = sb.substring(6, 11); System.out.println(subStr);
Output result:
World
Explanation: In the above example, the subcharacters are also obtained from the string "Hello World" String "World". By calling the substring(6, 11) method of sb, startIndex is set to 6 and endIndex is set to 11, specifying to extract the substring from index 6 to index 11. Therefore, the output is "World".
It should be noted that the substring() method of the StringBuffer class returns a new String object instead of modifying the original StringBuffer object. This means that modifications to the returned substring will not affect the original StringBuffer object.
Summary:
Using the substring() method of the StringBuffer class can easily obtain the substring in the string. By specifying the starting index and ending index to intercept the required substring, it can flexibly meet different needs. In actual development, we can use this function according to specific business logic to better process and operate strings.
The above is the detailed content of Use the substring() method of the StringBuffer class to obtain a substring. For more information, please follow other related articles on the PHP Chinese website!