StringBuilder用法
时间: 2024-06-06 12:06:52 浏览: 11
StringBuilder类是一个可变的字符串类,可以在字符串中插入、删除、替换、追加字符等操作,性能比较高。
1. 创建StringBuilder对象:
StringBuilder str = new StringBuilder(); // 创建一个空的StringBuilder对象
StringBuilder str = new StringBuilder("hello"); // 创建一个包含字符串"hello"的StringBuilder对象
2. 追加字符:
str.append('c'); // 往末尾添加一个字符
str.append(" world"); // 往末尾添加一个字符串
3. 插入字符:
str.insert(2, 'c'); // 在第2个位置插入一个字符
str.insert(2, "c"); // 在第2个位置插入一个字符串
4. 删除字符:
str.deleteCharAt(2); // 删除第2个字符
str.delete(2, 4); // 删除第2个到第4个字符
5. 替换字符:
str.replace(2, 4, "c"); // 将第2个到第4个字符替换为"c"
6. 转换为字符串:
String s = str.toString(); // 将StringBuilder对象转换为String对象
7. 获取长度:
int len = str.length(); // 获取StringBuilder对象的长度
8. 获取指定位置的字符:
char c = str.charAt(2); // 获取第2个位置的字符
9. 反转字符串:
str.reverse(); // 将字符串反转
10. 清空字符串:
str.setLength(0); // 清空字符串
注意:在多线程环境下,StringBuilder是不安全的,应该使用StringBuffer类。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)