前言
当我们需要对字符串进行大量的修改时,可以使用StringBuilder和StringBuffer类来完成。
和String类不同,StringBuilder和StringBuffer类的对象在堆字符串进行编辑时,不会创建大量无用的对象出来。
StringBuilder类在Java 5中被引入,其和StringBuffer类主要的不同是:StringBuilder类的方法不是线程安全的(非同步的)。
【面试题:StringBuilder和StringBuffer有什么区别?】
StringBuilder比StringBuffer运行的更快,因此在可能的情况下更推荐使用StringBuilder。然而,如果需要考虑线程安全的话,最好是选择StringBuffer。
程序实例
public class Test {
public static void main(String args[]) {
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
}
}
程序运行输出结果如下:
test String Buffer
StringBuffer类的方法
下表中列出了StringBuffer中比较重要的方法:
序号 | 方法&描述 |
---|---|
1 | public StringBuffer append(String s) 将参数中的字符拼接到对象后面,返回拼接后的对象。 |
2 | public StringBuffer reverse() 将对象的值进行反转。 |
3 | public delete(int start, int end) 删除指定起始和终止位置的字符串。 |
4 | public insert(int offset, int i) 在指定位置插入新的字符串。 |
5 | replace(int start, int end, String str) 替换指定起始和终止位置的字符串。 |
下面列出的是与String类非常相似的其他方法(set方法除外):
序号 | 方法&描述 |
---|---|
1 | int capacity() 返回StringBuffer对象的容量。 |
2 | char charAt(int index) 返回指定位置的字符。 |
3 | void ensureCapacity(int minimumCapacity) 确保缓冲区的容量至少等于指定的最小值。 |
4 | void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 将指定范围的字符复制到char数组中。 |
5 | int indexOf(String str) 返回指定子字符串首次出现在该对象中的索引。 |
6 | int indexOf(String str, int fromIndex) 从指定位置开始,返回指定子字符串首次出现在该对象中的索引。 |
7 | int lastIndexOf(String str) 返回指定子字符串最后一次出现在该对象中的索引。 |
8 | int lastIndexOf(String str, int fromIndex) 从指定位置开始,返回指定子字符串最后一次出现在该对象中的索引。 |
9 | int length() 返回StringBuffer对象的长度(字符数)。 |
10 | void setCharAt(int index, char ch) 将指定位置的字符替换成新的字符。 |
11 | void setLength(int newLength) 设置StringBuffer对象的长度。. |
12 | CharSequence subSequence(int start, int end) 提取指定范围的字符,按CharSequence类型对象返回。 |
13 | String substring(int start) 返回从指定位置开始到对象结尾的字符串。 |
14 | String substring(int start, int end) 返回指定范围的子串 |
15 | String toString() 将StringBuffer对象转换为String类对象。 |
关注公众号「小白轻松学编程」
更多交流,欢迎微信搜索并关注公众号「 小白轻松学编程 」!
博客里所有教程会第一时间在公众号上更新哟,扫码关注一下吧~