今天接着昨天的写,关于构建字符串的一些事情。
昨天提到的用加号连接字符串,实际上效率很低,原因是每次连接字符串都要新建一个新的对象,在空间和时间上都得不偿失。StringBuilder类可以解决这个问题,它对字符串的构建操作必须在一个单线程中。如果需要在多线程中处理字符串,可以使用效率稍低的StringBuffer类。
以下大部分内容来自官方的API文档,详情请见:Java Platform SE 8 API Documents
构造器可有四种重载:
Constructor and Description |
---|
StringBuilder()
Constructs a string builder with no characters in it and an initial capacity of 16 characters.
|
StringBuilder(CharSequence seq)
Constructs a string builder that contains the same characters as the specified
CharSequence .
|
StringBuilder(int capacity)
Constructs a string builder with no characters in it and an initial capacity specified by the
capacity argument.
|
StringBuilder(String str)
Constructs a string builder initialized to the contents of the specified string.
|
可以看出,如果括号里没有参数,则新建一个空串(不是null串),并将容量初始化为16。例如:
StringBuilder sb = new StringBuilder();
System.out.println(sb);
将会打印“”。
下面来看看StringBuilder类的各种方法:
1、append()方法
append()方法有很多重载,下面的表格详细描述了这组方法:
Modifier and Type | Method and Description |
---|---|
StringBuilder | append(boolean b)
Appends the string representation of the
boolean argument to the sequence.
|
StringBuilder | append(char c)
Appends the string representation of the
char argument to this sequence.
|
StringBuilder | append(char[] str)
Appends the string representation of the
char array argument to this sequence.
|
StringBuilder | append(char[] str, int offset, int len)
Appends the string representation of a subarray of the
char array argument to this sequence.
|
StringBuilder | append(CharSequence s)
Appends the specified character sequence to this
Appendable.
|
StringBuilder | append(CharSequence s, int start, int end)
Appends a subsequence of the specified
CharSequence to this sequence.
|
StringBuilder | append(double d)
Appends the string representation of the
double argument to this sequence.
|
StringBuilder | append(float f)
Appends the string representation of the
float argument to this sequence.
|
StringBuilder | append(int i)
Appends the string representation of the
int argument to this sequence.
|
StringBuilder | append(long lng)
Appends the string representation of the
long argument to this sequence.
|
StringBuilder | append(Object obj)
Appends the string representation of the
Object argument.
|
StringBuilder | append(String str)
Appends the specified string to this character sequence.
|
StringBuilder | append(StringBuffer sb)
Appends the specified
StringBuffer to this sequence.
|
StringBuilder | appendCodePoint(int codePoint)
Appends the string representation of the
codePoint argument to this sequence.
|
总结成一句话就是啥都能被append。。。 举个例子:
StringBuilder sb = new StringBuilder("I'm a ");
sb.append(20);
sb.append("-year-old programmer.");
String appended = sb.toString();
System.out.println(appended);
将会打印“I'm a 20-year-old programmer.”。
2、capacity()方法
capacity()方法可以用户获取当前容量。这个就不举例子了。同理的ensureCapacity()方法也就不再赘述了。
3、delete()方法
删除方法有以下两种:
StringBuilder | delete(int start, int end)
Removes the characters in a substring of this sequence.
|
StringBuilder | deleteCharAt(int index)
Removes the
char at the specified position in this sequence.
|
比如:
StringBuilder sb = new StringBuilder("The MouseEvent interface provides specific contextual information associated with Mouse events.");
sb.delete(4, 15);
String deleted = sb.toString();
System.out.println(deleted);
将会打印“The interface provides specific contextual information associated with Mouse events.”。注意,左闭右开的规则在这里仍然适用。
4、indexOf()方法与lastIndexOf()方法
与String类的indexOf()方法类似,这两个方法也用于查找子串并返回第一个找到的位置。
int | indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
|
int | indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
|
int | lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
|
int | lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
|
5、insert()方法
插入方法也有很多重载:
StringBuilder | insert(int offset, boolean b)
Inserts the string representation of the
boolean argument into this sequence.
|
StringBuilder | insert(int offset, char c)
Inserts the string representation of the
char argument into this sequence.
|
StringBuilder | insert(int offset, char[] str)
Inserts the string representation of the
char array argument into this sequence.
|
StringBuilder | insert(int index, char[] str, int offset, int len)
Inserts the string representation of a subarray of the
str array argument into this sequence.
|
StringBuilder | insert(int dstOffset, CharSequence s)
Inserts the specified
CharSequence into this sequence.
|
StringBuilder | insert(int dstOffset, CharSequence s, int start, int end)
Inserts a subsequence of the specified
CharSequence into this sequence.
|
StringBuilder | insert(int offset, double d)
Inserts the string representation of the
double argument into this sequence.
|
StringBuilder | insert(int offset, float f)
Inserts the string representation of the
float argument into this sequence.
|
StringBuilder | insert(int offset, int i)
Inserts the string representation of the second
int argument into this sequence.
|
StringBuilder | insert(int offset, long l)
Inserts the string representation of the
long argument into this sequence.
|
StringBuilder | insert(int offset, Object obj)
Inserts the string representation of the
Object argument into this character sequence.
|
StringBuilder | insert(int offset, String str)
Inserts the string into this character sequence.
|
对于刚才delete()方法中使用的例子,我们加上一行:
sb.insert(4, "MouseEvent ");
就能恢复原始的字符串。
6、replace()方法
该替换方法与String()类中的替换方法类似,再次也不再赘述。
StringBuilder | replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the specified
String .
|
7、reverse()方法
该方法可以将字符串倒置。
StringBuilder | reverse()
Causes this character sequence to be replaced by the reverse of the sequence.
|
比如:
StringBuilder sb = new StringBuilder("The MouseEvent interface provides specific contextual information associated with Mouse events.");
sb.reverse();
String reversed = sb.toString();
System.out.println(reversed);
将会打印“.stneve esuoM htiw detaicossa noitamrofni lautxetnoc cificeps sedivorp ecafretni tnevEesuoM ehT”。
8、截取子串
可以用subSequence()方法和substring()方法截取子串,具体如下:
CharSequence | subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
|
String | substring(int start)
Returns a new
String that contains a subsequence of characters currently contained in this character sequence.
|
String | substring(int start, int end)
Returns a new
String that contains a subsequence of characters currently contained in this sequence.
|
不再赘述。
9、setLength()方法
这是一个从头截取子串的方法。
void | setLength(int newLength)
Sets the length of the character sequence.
|
比如:
StringBuilder sb = new StringBuilder("The MouseEvent interface provides specific...");
sb.setLength(24);
String cutdown = sb.toString();
System.out.println(cutdown);
将会打印“The MouseEvent interface”。类似地,还有一个setCharAt()方法:
void | setCharAt(int index, char ch)
The character at the specified index is set to
ch .
|
10、trimToSize()方法
这个方法会将新建StringBuilder时或后续操作过后多出的空间回收掉。
void | trimToSize()
Attempts to reduce storage used for the character sequence.
|
比如:
StringBuilder sb = new StringBuilder("The MouseEvent interface provides specific..."); // 45个字符
System.out.println("Original capacity: " + sb.capacity());
sb.trimToSize();
System.out.println("After trimmed: " + sb.capacity());
会打印:
Original capacity: 61
After trimmed: 45其他方法就暂时不说了,更多具体的内容还是得参考API文档的哈。所有的超链接我都保留了下来。