温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java StringBuffer如何插入字符串

发布时间:2025-11-03 19:27:27 来源:亿速云 阅读:102 作者:小樊 栏目:编程语言

在Java中,StringBuffer 类提供了多种方法来插入字符串。以下是一些常用的插入方法:

  1. append():在StringBuffer对象的末尾追加字符串。
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb.toString()); // 输出 "Hello World"
  1. insert(int offset, String str):在指定的偏移量(索引)处插入字符串。
StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, " Beautiful");
System.out.println(sb.toString()); // 输出 "Hello Beautiful World"
  1. 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"
  1. insert(int offset, boolean b):在指定的偏移量(索引)处插入布尔值。
StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, true);
System.out.println(sb.toString()); // 输出 "Hello trueWorld"
  1. insert(int offset, char c):在指定的偏移量(索引)处插入字符。
StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, '!');
System.out.println(sb.toString()); // 输出 "Hello! World"
  1. 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,因为它的性能更高。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI