当对字符串进行修改的时候,需要使用stringbuffer和stringbuilder类。
和string类不同的是,stringbuffer和stringbuilder类的对象能够被多次的修改,并且不产生新的未使用对象。
stringbuilder类在java 5中被提出,它和stringbuffer之间的最大不同在于stringbuilder的方法不是线程安全的(线程安全就是多线程访问时,采用了加锁机制,当一个线程访问该类的某个数据时,进行保护,其他线程不能进行访问直到该线程读取完,其他线程才可使用。不会出现数据不一致或者数据污染。线程不安全就是不提供数据访问保护,有可能出现多个线程先后更改数据造成所得到的数据是脏数据)。
由于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类支持的主要方法:
序号 | 方法描述 |
---|---|
1 | public stringbuffer append(string s) 将指定的字符串追加到此字符序列。 |
2 | public stringbuffer reverse() 将此字符序列用其反转形式取代。 |
3 | public delete(int start, int end) 移除此序列的子字符串中的字符。 |
4 | public insert(int offset, int i) 将 int 参数的字符串表示形式插入此序列中。 |
5 | replace(int start, int end, string str) 使用给定 string 中的字符替换此序列的子字符串中的字符。 |
下面的列表里的方法和string类的方法类似:
序号 | 方法描述 |
1 | int capacity() 返回当前容量。 |
2 | char charat(int index) 返回此序列中指定索引处的 char 值。 |
3 | void ensurecapacity(int minimumcapacity) 确保容量至少等于指定的最小值。 |
4 | void getchars(int srcbegin, int srcend, char[] dst, int dstbegin) 将字符从此序列复制到目标字符数组 dst 。 |
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() 返回长度(字符数)。 |
10 | void setcharat(int index, char ch) 将给定索引处的字符设置为 ch 。 |
11 | void setlength(int newlength) 设置字符序列的长度。 |
12 | charsequence subsequence(int start, int end) 返回一个新的字符序列,该字符序列是此序列的子序列。 |
13 | string substring(int start) 返回一个新的 string ,它包含此字符序列当前所包含的字符子序列。 |
14 | string substring(int start, int end) 返回一个新的 string ,它包含此序列当前所包含的字符子序列。 |
15 | string tostring() 返回此序列中数据的字符串表示形式。 |