用StringBuilder构建字符串

       今天接着昨天的写,关于构建字符串的一些事情。

       昨天提到的用加号连接字符串,实际上效率很低,原因是每次连接字符串都要新建一个新的对象,在空间和时间上都得不偿失。StringBuilder类可以解决这个问题,它对字符串的构建操作必须在一个单线程中。如果需要在多线程中处理字符串,可以使用效率稍低的StringBuffer类。

       以下大部分内容来自官方的API文档,详情请见:Java Platform SE 8 API Documents

       构造器可有四种重载:

Constructors
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 TypeMethod and Description
StringBuilderappend(boolean b)
Appends the string representation of the  boolean argument to the sequence.
StringBuilderappend(char c)
Appends the string representation of the  char argument to this sequence.
StringBuilderappend(char[] str)
Appends the string representation of the  char array argument to this sequence.
StringBuilderappend(char[] str, int offset, int len)
Appends the string representation of a subarray of the  char array argument to this sequence.
StringBuilderappend(CharSequence s)
Appends the specified character sequence to this  Appendable.
StringBuilderappend(CharSequence s, int start, int end)
Appends a subsequence of the specified  CharSequence to this sequence.
StringBuilderappend(double d)
Appends the string representation of the  double argument to this sequence.
StringBuilderappend(float f)
Appends the string representation of the  float argument to this sequence.
StringBuilderappend(int i)
Appends the string representation of the  int argument to this sequence.
StringBuilderappend(long lng)
Appends the string representation of the  long argument to this sequence.
StringBuilderappend(Object obj)
Appends the string representation of the  Object argument.
StringBuilderappend(String str)
Appends the specified string to this character sequence.
StringBuilderappend(StringBuffer sb)
Appends the specified  StringBuffer to this sequence.
StringBuilderappendCodePoint(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()方法

       删除方法有以下两种:

StringBuilderdelete(int start, int end)
Removes the characters in a substring of this sequence.
StringBuilderdeleteCharAt(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()方法类似,这两个方法也用于查找子串并返回第一个找到的位置。

intindexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
intindexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
intlastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
intlastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.

       5、insert()方法

       插入方法也有很多重载:

StringBuilderinsert(int offset, boolean b)
Inserts the string representation of the  boolean argument into this sequence.
StringBuilderinsert(int offset, char c)
Inserts the string representation of the  char argument into this sequence.
StringBuilderinsert(int offset, char[] str)
Inserts the string representation of the  char array argument into this sequence.
StringBuilderinsert(int index, char[] str, int offset, int len)
Inserts the string representation of a subarray of the  str array argument into this sequence.
StringBuilderinsert(int dstOffset, CharSequence s)
Inserts the specified  CharSequence into this sequence.
StringBuilderinsert(int dstOffset, CharSequence s, int start, int end)
Inserts a subsequence of the specified  CharSequence into this sequence.
StringBuilderinsert(int offset, double d)
Inserts the string representation of the  double argument into this sequence.
StringBuilderinsert(int offset, float f)
Inserts the string representation of the  float argument into this sequence.
StringBuilderinsert(int offset, int i)
Inserts the string representation of the second  int argument into this sequence.
StringBuilderinsert(int offset, long l)
Inserts the string representation of the  long argument into this sequence.
StringBuilderinsert(int offset, Object obj)
Inserts the string representation of the  Object argument into this character sequence.
StringBuilderinsert(int offset, String str)
Inserts the string into this character sequence.

对于刚才delete()方法中使用的例子,我们加上一行:

sb.insert(4, "MouseEvent ");
就能恢复原始的字符串。

       6、replace()方法

       该替换方法与String()类中的替换方法类似,再次也不再赘述。

StringBuilderreplace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the specified  String.

       

       7、reverse()方法

       该方法可以将字符串倒置。

StringBuilderreverse()
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()方法截取子串,具体如下:

CharSequencesubSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
Stringsubstring(int start)
Returns a new  String that contains a subsequence of characters currently contained in this character sequence.
Stringsubstring(int start, int end)
Returns a new  String that contains a subsequence of characters currently contained in this sequence.

       不再赘述

       9、setLength()方法

       这是一个从头截取子串的方法。

voidsetLength(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()方法:

voidsetCharAt(int index, char ch)
The character at the specified index is set to  ch.
作用是改变某个位置的字符,就不举例子了。

       10、trimToSize()方法

       这个方法会将新建StringBuilder时或后续操作过后多出的空间回收掉。

voidtrimToSize()
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文档的哈。所有的超链接我都保留了下来。

       在进阶的路上,欢迎各位大侠指正。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值