gpt4 book ai didi

java - StringBuffer appen 和 insert 有什么区别?

转载 作者:行者123 更新时间:2023-11-30 06:57:55 27 4
gpt4 key购买 nike

在我的 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 thissequence.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 appen 和 insert 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170276/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com