stringbuffer类-爱代码爱编程
StringBuffer是一个可变的字符串类,提供了许多方法来修改和操作字符串。以下是一些常见的StringBuffer方法及其示例:
- append():将指定的字符串连接到现有字符串的末尾。
StringBuffer sb = new StringBuffer("Hello");
sb.append(" world!");
System.out.println(sb.toString()); // 输出 "Hello world!"
- insert():在指定位置插入指定的字符串。
StringBuffer sb = new StringBuffer("Hello");
sb.insert(2, "world");
System.out.println(sb.toString()); // 输出 "Heworldllo"
- replace():用指定的字符串替换从start到end位置的字符。
StringBuffer sb = new StringBuffer("Hello world!");
sb.replace(6, 11, "Java");
System.out.println(sb.toString()); // 输出 "Hello Java!"
- delete():删除从start到end位置的字符。
StringBuffer sb = new StringBuffer("Hello world!");
sb.delete(6, 11);
System.out.println(sb.toString()); // 输出 "Hello!"
- reverse():反转字符串。
StringBuffer sb = new StringBuffer("Hello world!");
sb.reverse();
System.out.println(sb.toString()); // 输出 "!dlrow olleH"
- length():返回当前字符串长度。
StringBuffer sb = new StringBuffer("Hello world!");
System.out.println(sb.length()); // 输出 12
- capacity():返回当前容量(能够容纳的字符数量)。
StringBuffer sb = new StringBuffer("Hello world!");
System.out.println(sb.capacity()); // 输出 21