Java StringBuilder类API方法指南

x33g5p2x  于2021-08-18 转载在 Java  
字(16.2k)|赞(0)|评价(0)|浏览(549)

在本指南中,我们将通过大量的例子讨论Java StringBuilder类的所有构造函数和方法。

###关于StringBuilder类的关键点

  • Java StringBuilderclass是用来创建可变(可修改)的字符串。Java StringBuilderclass与StringBuffer类相同,只是它是非同步的。它从JDK 1.5开始使用。
  • 一个可变的字符序列。该类提供了一个与StringBuffer兼容的API,但不保证同步性。该类被设计为在字符串缓冲区被单线程使用的地方(通常是这样),作为StringBuffer的直接替代品使用。
  • 在可能的情况下,建议优先使用该类而不是StringBuffer,因为它在大多数实现中都会更快。
  • 对StringBuilder的主要操作是append和insert方法,这些方法被重载以接受任何类型的数据。每个方法都有效地将给定的数据转换为一个字符串,然后将该字符串的字符追加或插入到字符串生成器中。附加方法总是在构建器的末尾添加这些字符;插入方法在指定的位置添加这些字符。
  • 正如我们所知,StringBuilder的实例在多线程中使用是不安全的。如果需要这种同步,那么建议使用StringBuffer

StringBuilder类的层次结构 

下面的类图显示了StringBuilder类的层次结构。所有实现的接口。
Serializable, Appendable, CharSequence.

从上面的类图中,StringBuilder扩展了AbstractStringBuilder类,该类内部实现了Appendable、CharSequence接口。在StringBuilder JavaDoc 8上阅读更多关于层次结构的内容。

StringBuilder构造函数

StringBuilder定义了这四个构造函数。

  • StringBuilder()
  • StringBuilder(String str)
  • StringBuilder(int capacity)
  • StringBuilder(CharSequence seq)

StringBuilder()

构建一个没有字符的字符串生成器,初始容量为16个字符。

StringBuilder builder = new StringBuilder();
System.out.println(builder.capacity());

输出:

16

StringBuilder(String str)

构建一个初始化为指定字符串内容的字符串生成器。字符串生成器的初始容量是16加上字符串参数的长度。

例子。

StringBuilder builder2 = new StringBuilder("javaguides");
System.out.println(builder2.capacity());

输出。

26

StringBuilder(int capacity)

构建一个没有字符的字符串生成器,初始容量由容量参数指定。

例子。

StringBuilder builder4 = new StringBuilder(10);
System.out.println(builder4.capacity());

输出。

10

StringBuilder(CharSequence seq)

构建一个字符串生成器,包含与指定的CharSequence相同的字符。字符串生成器的初始容量是16加上CharSequence参数的长度。

例如。

CharSequence charSequence = new String("charSequence");
StringBuilder builder3 = new StringBuilder(charSequence);
System.out.println(builder3.capacity());

输出。

28

StringBuilder APIs/方法

append()方法

它有几个重载版本。下面是它所有的形式。

  1. StringBuilder append(boolean b) - 将布尔参数的字符串表示法添加到序列中。
  2. StringBuilder append(char c) - 将char参数的字符串表示法添加到该序列中。
  3. StringBuilder append(char[] str) - 将char数组参数的字符串表示法添加到该序列中。
  4. StringBuilder append(char[] str, int offset, int len) - 将char数组参数的子数组的字符串表示法添加到此序列中。
  5. StringBuilder append(CharSequence s) - 将指定的CharSequence追加到此序列中。
  6. StringBuilder append(CharSequence s, int start, int end) - 将指定的CharSequence的一个子序列添加到这个序列中。
  7. StringBuilder append(double d) - 将双倍参数的字符串表示法添加到这个序列中。
  8. StringBuilder append(float f) - 在此序列中添加浮动参数的字符串表示。
  9. StringBuilder append(int i) - 将int参数的字符串表示法添加到这个序列中。
  10. StringBuilder append(long lng) - 将长参数的字符串表示法添加到这个序列中。
  11. StringBuilder append(Object obj) - 向该序列添加Object参数的字符串表示。
  12. StringBuilder append(String str) - 将指定的字符串追加到这个字符序列中。
  13. StringBuilder append(StringBuffer sb) - 将指定的StringBuffer追加到该序列中。
  14. StringBuilder appendCodePoint(int codePoint) - 将codePoint参数的字符串表示法添加到此序列中。
    让我们用例子来证明每个append()方法。

例子。这个程序演示了上述14种append方法的用法。

public class AppendExample {
 public static void main(String[] args) {
  // 13 append overloaded methods

  StringBuilder builder;
  // append String

  // Append String
  builder = new StringBuilder().append("guides");
  System.out.println("Append string : " + builder);
  
  // Append char
  builder = new StringBuilder().append('c');
  System.out.println("Append char : " + builder);
  // Append Object
  builder = new StringBuilder().append(new Object().getClass());
  System.out.println("Append Object : " + builder);
  
  // Append chars
  char[] chars = { 'j', 'a', 'v', 'a' };
  builder = new StringBuilder().append(chars);
  System.out.println("Append chars : " + builder);
  
  // Append charSequence
  builder = new StringBuilder().append("charSequence");
  System.out.println("Append charSequence : " + builder);
  
  // Append Double
  builder = new StringBuilder().append(10.0d);
  System.out.println("Append Double : " + builder);
  
  // Append Float
  builder = new StringBuilder().append(10.5f);
  System.out.println("Append Float : " + builder);
  
  // Append int
  builder = new StringBuilder().append(100);
  System.out.println("Append int : " + builder);
  
  // Append Boolean
  builder = new StringBuilder().append(true);
  System.out.println("Append Boolean : " + builder);
  
  // Append Long
  builder = new StringBuilder().append(100000);
  System.out.println("Append Long : " + builder);
  
  // Appends the specified StringBuffer to this sequence
  builder = new StringBuilder().append(new StringBuffer("stringbuffer"));
  System.out.println("Append StringBuffer : " + builder);
  
  // Appends the string representation of a subarray of the char array.
  builder = new StringBuilder().append(chars, 1, 3);
  System.out.println("Append subarray of the char array : " + builder);
  
  // Appends a subsequence of the specified CharSequence to this sequence.
  builder = new StringBuilder().append("javaguides", 0, 9);
  System.out.println("Append CharSequence : " + builder);
  
  // Appends the string representation of the codePoint argument to this
  // sequence.
  builder = new StringBuilder("javaguides").appendCodePoint(0);
  System.out.println("Append appendCodePoint : " + builder);

 }
}

输出。

Append string : guides
Append char : c
Append Object : class java.lang.Object
Append chars : java
Append charSequence : charSequence
Append Double : 10.0
Append Float : 10.5
Append int : 100
Append Boolean : true
Append Long : 100000
Append StringBuffer : stringbuffer
Append subarray of the char array : ava
Append CharSequence : javaguide
Append appendCodePoint : javaguides

capacity()

该方法返回当前的容量。容量是可用于新插入的字符的存储量,超过这个容量将发生分配。

例子。这个简单的程序演示了capacity()方法的用法。

public class CapacityExample {
 public static void main(String[] args) {
  StringBuilderbuilder = new StringBuilder("javaguides");
  int capacity = builder.capacity();
  
  // inital capacity
  System.out.println(new StringBuilder().capacity());
  
  // intial capacity 16 + number of characters in string
  System.out.println("Capacity of the string :: " + capacity);
 }
}

输出。

16
Capacity of the string :: 26

charAt(int index)

返回指定索引处的char值。索引范围从0到length()-1。序列的第一个char值在索引0处,下一个在索引1处,以此类推,如同数组的索引。

为了从一个字符串中提取单个字符,你可以通过charAt( )方法直接引用单个字符。
这个方法会抛出IndexOutOfBoundsException--如果一个索引是负的或者大于等于一个length()。

例1: 返回这个字符串中指定索引处的char值。第一个char值在索引0处。

StringBuilder builder = new StringBuilder("Welcome to string handling guide");
char ch1 = builder.charAt(0);
char ch2 = builder.charAt(5);
char ch3 = builder.charAt(11);
char ch4 = builder.charAt(20);
System.out.println("Character at 0 index is: " + ch1);
System.out.println("Character at 5th index is: " + ch2);
System.out.println("Character at 11th index is: " + ch3);
System.out.println("Character at 20th index is: " + ch4);

输出。

Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n

例2:举例说明如何获得字符串的第一个和最后一个字符

public static void charAtExample2() {
StringBuilder builder = new StringBuilder("Java Guides");
int strLength = builder .length() - 1;
// Fetching first character
System.out.println("Character at 0 index is: " + builder .charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + builder .charAt(strLength));

输出。

Character at 0 index is: J
Character at last index is: s

codePointAt(int index)

该方法返回指定索引处的字符(Unicode代码点)。索引指的是char值(Unicode代码单位),范围从0到length()-1。

如果索引参数为负数或不小于这个字符串的长度,该方法会抛出IndexOutOfBoundsException。
例子。

public class CodePointAtExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  int unicode = builder.codePointAt(0);
  System.out.println("the character (Unicode code point) at the specified index is :: " + unicode);
 }
}

输出;

the character (Unicode code point) at the specified index is :: 106

codePointBefore(int index)

返回指定索引前的字符(Unicode码位)。索引指的是char值(Unicode代码单位),范围从1到length()。

例子。

public class CodePointBeforeExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  int unicode = builder.codePointBefore(1);
  System.out.println("the character (Unicode code point) at the before specified index is :: " + unicode);
 }
}

输出。

the character (Unicode code point) at the before specified index is :: 106

codePointCount(int beginIndex, int endIndex)

该方法返回该字符串指定文本范围内的Unicode代码点的数量。文本范围从指定的beginIndex开始,延伸到索引endIndex-1的字符。

如果beginIndex为负数,或者endIndex大于此字符串的长度,或者beginIndex大于endIndex,此方法会抛出IndexOutOfBoundsException。
例子。

public class CodePointCountExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  System.out.println("length of the string :: " + builder.length());
  int unicode = builder.codePointCount(0, builder.length());
  System.out.println("the character (Unicode code point) at the specified index is :: " + unicode);
 }
}

delete(int start, int end)

这个方法删除这个序列的一个子串中的字符。子串从指定的start开始,延伸到索引end-1的字符,如果没有这样的字符,则延伸到序列的末端。如果start等于end,则不做任何改变。

例子。使用delete()方法从字符串'javaguides'中删除子串'java'的例子。

public class DeleteExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  
  // start with index and end with end -1
  StringBuilder subBuilder = buffer.delete(0, 4);
  System.out.println("Delete string 'java' from string 'javaguides' : " + subBuilder.toString());
 }
}

输出。

Delete string 'java' from string 'javaguides' : guides

deleteCharAt(int index)

这个方法删除这个序列中指定位置上的char。这个序列被缩短了一个字符。

这个方法抛出了StringIndexOutOfBoundsException - 如果索引是负的或者大于等于一个length()。
例子。使用deleteCharAt()方法从字符串 "javaguides "中删除字符 "g "的例子。

输出。

Delete char 'g' from string 'javaguides' : javauides

ensureCapacity(int minimumCapacity)

确保容量至少等于指定的最小值。如果当前容量小于参数,那么将分配一个新的内部数组,容量更大。新的容量是以下两者中较大的。

  • 最小容量参数。
  • 旧容量的两倍,加上2。
    例子。使用ensureCapacity()方法确保字符串缓冲区的容量的例子。
public class EnsureCapacityExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder();
  builder.ensureCapacity(11);
     System.out.println(builder.capacity());
 }
}

输出:

16

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

将该序列中的字符复制到目标字符数组dst中。

示例。将此序列中的字符复制到目标字符数组dst中的例子。

public class GetCharsExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  char[] dst = new char[builder.length()];
  builder.getChars(0, builder.length(), dst, 0);
  
  for (char c : dst) {
   System.out.println(c);
  }
 }
}

输出。

j
a
v
a
g
u
i
d
e
s

indexOf()方法

有两种形式的indexOf()方法

  • indexOf(String str) - 返回指定子串的第一次出现在这个字符串中的索引。
  • indexOf(String str, int fromIndex)- 返回指定子串第一次出现在这个字符串中的索引,从指定的索引开始。
    例子。这是一个简单的程序,用来演示2个具有不同签名的indexOf()方法。
public class IndexOfExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  
  // method 1
  int index = builder.indexOf("guides");
  System.out.println(index);
  
  // method2
  index = builder.indexOf("guides", 3);
  System.out.println(index);
 }
}

输出:

4
4

insert()方法

insert()方法有12个重载版本。下面是它所有的形式。

  1. StringBuilder insert(int offset, boolean b) - 将布尔参数的字符串表示法插入这个序列中。
  2. StringBuilder insert(int offset, char c) - 在这个序列中插入char参数的字符串表示。
  3. StringBuilder insert(int offset, char[] str) - 在此序列中插入char数组参数的字符串表示。
  4. StringBuilder insert(int index, char[] str, int offset, int len) - 在这个序列中插入str数组参数的子数组的字符串表示。
  5. StringBuilder insert(int dstOffset, CharSequence s) - 将指定的CharSequence插入到这个序列中。
  6. StringBuilder insert(int dstOffset, CharSequence s, int start, int end) - 将指定的CharSequence的一个子序列插入到这个序列中。
  7. StringBuilder insert(int offset, double d) - 将双倍参数的字符串表示插入到这个序列中。
  8. StringBuilder insert(int offset, float f) - 在此序列中插入浮动参数的字符串表示。
  9. StringBuilder insert(int offset, int i) - 在此序列中插入第二个int参数的字符串表示。
  10. StringBuilder insert(int offset, long l) - 在这个序列中插入长参数的字符串表示。
  11. StringBuilder insert(int offset, Object obj) - 将Object参数的字符串表示插入到这个字符序列中。
  12. StringBuilder insert(int offset, String str) - 将字符串插入到这个字符序列中。
    例子。下面的简单程序演示了所有insert()重载方法的用法。
public class InsertExample {
 public static void main(String[] args) {

  // 12 insert overloaded method
  StringBuilder builder = new StringBuilder("javaguides").insert(1, true);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 'J');
  System.out.println(builder.toString());

  char[] chars = { 'd', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r' };
  builder = new StringBuilder("javaguides").insert(4, chars);
  System.out.println(builder.toString());

  CharSequence charSequence = new StringBuilder("J2EE/");
  builder = new StringBuilder("javaguides").insert(0, charSequence);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100.0d);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100.0f);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100l);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, new Object());
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, "ultimate");
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, chars, 0, chars.length);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, charSequence, 0, charSequence.length());
  System.out.println(builder.toString());
 }
}

输出:

jtrueavaguides
Jjavaguides
javadeveloperguides
J2EE/javaguides
100.0javaguides
100.0javaguides
100javaguides
100javaguides
java.lang.Object@15db9742javaguides
ultimatejavaguides
developerjavaguides
J2EE/javaguides

lastIndexOf()方法

lastIndexOf()方法有两个重载版本。下面是它的所有形式。

int lastIndexOf(String str)- 返回这个字符串中指定子串的最右边出现的索引。
int lastIndexOf(String str, int fromIndex)- 返回指定子串最后出现在这个字符串中的索引。
例子。这个例子演示了两个lastIndexOf()重载方法的用法。

public class LastIndexOfExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");

  // method1
  int lastIndexOf = builder.lastIndexOf("guides");
  System.out.println(" last index of given string 'guides' in' "
    + builder.toString() + "' ::  " + lastIndexOf);

  // method 2
  lastIndexOf = builder.lastIndexOf("java", 3);
  System.out.println(" last index of given string 'java' in' "
     + builder.toString() + "' ::  " + lastIndexOf);
 }
}

输出:

last index of given string 'guides' in' javaguides' ::  4
 last index of given string 'java' in' javaguides' ::  0

length()

返回长度(字符数)。

例子。

public class LengthExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  int length = builder.length();
  System.out.println(" length of the string '" + builder + "' is :: " + length);
 }
}

输出。

length of the string 'javaguides' is :: 10

replace(int start, int end, String str)

用指定的String中的字符替换这个序列的子串中的字符。子串从指定的起始点开始,延伸到索引端-1的字符,如果没有这样的字符,则延伸到序列的末端。首先,子串中的字符被删除,然后在开始处插入指定的字符串。(如果有必要,这个序列将被延长以适应指定的字符串)。)

例子。使用replace()方法将字符串 "ja "替换为字符串 "java "的例子。

public class ReplaceExample {
 public static void main(String[] args) {
  StringBuilder buffer = new StringBuilder("jaguides");
  
  // replace ja with java- start index 0 and end index -1
  StringBuilder subBuffer = buffer.replace(0, 2, "java");
  
  System.out.println(subBuffer);
 }
}

输出。

javaguides

reverse()

导致该字符序列被该序列的反向所取代。

例子。使用reverse()方法反转给定的字符串 "javaguides "的例子。

public class ReverseExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  StringBuilder reverse = builder.reverse();
  System.out.println("Reversed string :" + reverse);
 }
}

输出。

Reversed string :sediugavaj

setCharAt(int index, char ch)

指定索引处的字符被设置为ch。

例子。使用setCharAt()方法在索引0处设置字符'J'的例子。

public class SetCharExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  builder.setCharAt(0, 'J');
  System.out.println(builder.toString());
 }
}

输出。

Javaguides

setLength(int newLength)

设置字符序列的长度。

例子。使用setLength()方法重置StringBuilder的长度的例子。

public class SetLengthExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  System.out.println("Before set length to 0 : " + builder.length());
  builder.setLength(0);
  System.out.println("After set length to 0 : " + builder.length());
 }
}

输出。

Before set length to 0 : 10
After set length to 0 : 0

substring()方法

substring()方法有两个重载版本。

  1. String substring(int start)- 返回一个新的字符串,该字符串包含当前包含在这个字符序列中的一个子序列的字符。
  2. String substring(int start, int end)- 返回一个新的字符串,该字符串包含当前包含在该序列中的字符的子序列。
    例子。这个例子演示了substring()方法的两个重载版本的用法。
public class SubStringExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  // substring from start to end
  String subStr = buffer.substring(0, builder.length());
  System.out.println("substring from 0 to length of the string : " + subStr);
  
  // print java
  System.out.println(builder.substring(0, 4));
  
  // print guides
  System.out.println(builder.substring(4, builder.length()));
 }
}

输出:

substring from 0 to length of the string : javaguides
java
guides

toString()

返回一个代表该序列中数据的字符串。

例子。

public class ToStringExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  System.out.println(builder.toString());
 }
}

输出。

javaguides

trimToSize()

试图减少用于字符序列的存储空间。

例子。

public class TrimToSizeExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides ");
  System.out.println(builder.capacity());
  builder.trimToSize();
  System.out.println(builder.capacity());
 }
}

输出。

27
11

查看我的从初学者到专家的顶级Java String Tutorial
**请发表意见,如果有任何建议来改进这个StringBuilder API指南,因为它对每个人都非常有用。

GitHub 仓库

参考资料

相关文章