Use java's StringBuilder.delete() function to delete a specified range of characters
StringBuilder is a variable string, and its delete() method can be used to delete a specified range of characters in the StringBuilder object. This article demonstrates the use of this method through code examples.
The following is a simple code example:
public class StringBuilderDeleteExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello, World!"); // 删除指定索引范围内的字符 sb.delete(7, 13); System.out.println(sb.toString()); } }
In the above code, we created a StringBuilder object sb, whose initial value is "Hello, World!". Then, we call the delete() method to delete characters with indexes from 7 to 13. Finally, use the toString() method to convert the StringBuilder object to a String and print it out.
Run the above code, the output result is "Hello!". As you can see, the delete() method deletes characters within the index range.
In addition to the delete(start, end) method, StringBuilder also provides several other methods for deleting characters. The following are some commonly used examples:
StringBuilder sb = new StringBuilder("Hello, World!"); sb.deleteCharAt(7); System.out.println(sb.toString()); // 输出结果为"Hello orld!"
StringBuilder sb = new StringBuilder("Hello, World!"); sb.delete(5); System.out.println(sb.toString()); // 输出结果为"Hello"
StringBuilder sb = new StringBuilder("Hello, World!"); sb.delete(0, 5); System.out.println(sb.toString()); // 输出结果为", World!"
It should be noted that the delete() method modifies the original StringBuilder object rather than returning a new StringBuilder object.
Summary:
This article introduces the use of Java's StringBuilder.delete() method to delete a specified range of characters through code examples. We can delete characters in the StringBuilder object through the delete(), deleteCharAt() and delete(start, end) methods. These methods can be selected according to specific needs and are flexible and convenient. You can use these methods according to your actual needs.
The above is the detailed content of Use java's StringBuilder.delete() function to delete a specified range of characters. For more information, please follow other related articles on the PHP Chinese website!