一、方法概述
StringBuilder的append()方法是用於將指定的字符串追加到此字符序列的末尾。該方法是StringBuilder類最為常用的方法之一。
//方法簽名 public StringBuilder append(String str)
二、方法參數
該方法只接受一個字符串參數:
- str:要添加到當前字符序列中的字符串。
三、方法返回值
該方法返回一個指向調用此方法的StringBuilder對象的引用。
四、方法示例
StringBuilder sb = new StringBuilder("This is a test!");
sb.append(" This is the second test.");
System.out.println(sb.toString());
輸出結果:This is a test! This is the second test.
五、方法詳解
1、追加字符串
append()方法最基本的功能是將指定的字符串添加到調用此方法的StringBuilder對象的末尾。
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString());
輸出結果:Hello World
2、追加指定類型的字符串
除了追加String類型的字符串以外,append()方法還可以追加int、double、char等類型的字符串。
//追加int類型的字符串
StringBuilder sb = new StringBuilder("Age: ");
int age = 18;
sb.append(age);
System.out.println(sb.toString());
//追加double類型的字符串
sb = new StringBuilder("Price: ");
double price = 25.50;
sb.append(price);
System.out.println(sb.toString());
//追加char類型的字符串
sb = new StringBuilder("First letter: ");
char letter = 'A';
sb.append(letter);
System.out.println(sb.toString());
輸出結果:
Age: 18
Price: 25.5
First letter: A
3、連續追加多個字符串
append()方法支持連續追加多個字符串。
StringBuilder sb = new StringBuilder("Hello");
sb.append(" ").append("World").append("!");
System.out.println(sb.toString());
輸出結果:Hello World!
4、追加字符串部分內容
append()方法還支持只追加字符串的一部分內容。
StringBuilder sb = new StringBuilder("Hello World!");
sb.append(" World", 0, 5);
System.out.println(sb.toString());
輸出結果:Hello World World
5、追加對象
append()方法還可以用來追加任意類型的對象,因為它會調用該對象的toString()方法來返回一個字符串並將其追加到StringBuilder對象的末尾。
StringBuilder sb = new StringBuilder("Person: ");
Person person = new Person("小明", 18);
sb.append(person);
System.out.println(sb.toString());
輸出結果:Person: Person{name=’小明’, age=18}
6、鏈式調用
append()方法支持鏈式調用,使得代碼更加簡潔易讀。
StringBuilder sb = new StringBuilder("Hello").append(" World").append("!");
System.out.println(sb.toString());
輸出結果:Hello World!
六、方法注意事項
在使用append()方法時,需要注意以下幾點:
- StringBuilder對象的初始容量不夠時,會進行自動擴容,但過大的StringBuilder對象會佔用過多的內存。
- 建議在追加大量字符串時使用append()方法,而不是使用”+”連接符,因為”+”連接符會創建大量的中間字符串,導致效率低下。
- 最好將StringBuilder對象聲明為局部變量,而不是全局變量,因為多線程訪問全局變量可能會出現線程安全問題。
七、總結
通過本篇文章的介紹,我們詳細了解了StringBuilder的append()方法的使用方法以及注意事項。在實際開發中,我們應該根據具體情況選擇使用StringBuilder的append()方法來優化代碼。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/258643.html
微信掃一掃
支付寶掃一掃