在Java中,StringBuffer 类提供了多种方法来插入字符串。以下是一些常用的插入方法:
append():在StringBuffer对象的末尾追加字符串。StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb.toString()); // 输出 "Hello World"
insert(int offset, String str):在指定的偏移量(索引)处插入字符串。StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, " Beautiful");
System.out.println(sb.toString()); // 输出 "Hello Beautiful World"
insert(int offset, char[] str):在指定的偏移量(索引)处插入字符数组。StringBuffer sb = new StringBuffer("Hello World");
char[] chars = {' ', 'P', 'l', 'e', 'a', 's', 'e'};
sb.insert(5, chars);
System.out.println(sb.toString()); // 输出 "Hello Beautiful World"
insert(int offset, boolean b):在指定的偏移量(索引)处插入布尔值。StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, true);
System.out.println(sb.toString()); // 输出 "Hello trueWorld"
insert(int offset, char c):在指定的偏移量(索引)处插入字符。StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, '!');
System.out.println(sb.toString()); // 输出 "Hello! World"
insert(int offset, int i):在指定的偏移量(索引)处插入整数。StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, 42);
System.out.println(sb.toString()); // 输出 "Hello 42World"
注意:StringBuffer 是线程安全的,而 StringBuilder 是非线程安全的。在不需要考虑线程安全的情况下,建议使用 StringBuilder,因为它的性能更高。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。