java - StringBuffer追加和插入有什么区别?

标签 java string stringbuffer

在我的java代码中我使用

StringBuffer sb = new StringBuffer();
String str = "";
sb.append(str + "abc"); //??
sb.insert(0,(str + "abc")); //??

任何人都可以告诉我这个 sb.append(str + "abc");sb.insert(0,(str + "abc"));

最佳答案

在您的代码中,如 String str = ""; 您看不到差异,但确实存在差异。

  • 第一个附加在末尾。
  • 在开头插入第二个。

看看这段代码:

1 附加:

String str = "abc";
StringBuilder sb = new StringBuilder("123");
sb.append("abc"); // str = "123abc"
//                             ↑ abc is appended at the end of sb

来自 API:

append(String) :

Appends the string representation of the char array argument to this sequence.


2插入:

String str = "abc";
StringBuilder sb0 = new StringBuilder("123");
sb.insert(0, str); // str = "abc123"
//                           ↑ abc is inserted at position 0 of sb0
StringBuilder sb1 = new StringBuilder("123");
sb.insert(1, str); // str = "1abc23"
//                            ↑ abc is inserted at position 1 of sb1
StringBuilder sb3 = new StringBuilder("123");
sb.insert(2, str); // str = "12abc3"
//                             ↑ abc is inserted at position 2 of sb2
StringBuilder sb4 = new StringBuilder("123");
sb.insert(3, str); // str = "123abc"
//                              ↑ abc is inserted at position 3 of sb2

所以...我们可以推断:StringBuilder.append == StringBuilder.insert(length)

insert(int offset, String str)

Inserts the string representation of the char array argument into this sequence. The characters of the array argument are inserted into the contents of this sequence at the position indicated by offset. The length of this sequence increases by the length of the argument.

关于java - StringBuffer追加和插入有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170276/

相关文章:

java - 从 PDFBox 剥离时的文本坐标

java - 具有相同实体的 Fetchtype.LAZY

C For 循环不起作用?

r - 填充数据框 R 中缺失的字符串值

java - 从 Integer 值转换为 StringBuffer(以零作为默认值)

java - Spring 集成 : Move file in remote SFTP location after processing

java - 我可以添加 hql 中多个表的金额吗

string - 如何在 zsh 完成中删除文件扩展名?

Java 程序输出应该是 true ,但它返回 false 为什么?

java - 将字符串变量重新分配给 StringBuffer 对象