Documentation

The Java™ Tutorials
Hide TOC
The StringBuilder ClassStringBuilder类
Trail: Learning the Java Language
Lesson: Numbers and Strings
Section: Strings

The StringBuilder ClassStringBuilder类

StringBuilder objects are like String objects, except that they can be modified.StringBuilder对象与String对象类似,只是它们可以修改。Internally, these objects are treated like variable-length arrays that contain a sequence of characters.在内部,这些对象被视为包含字符序列的可变长度数组。At any point, the length and content of the sequence can be changed through method invocations.在任何时候,都可以通过方法调用更改序列的长度和内容。

Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance.除非字符串生成器在代码更简单(请参阅本节末尾的示例程序)或性能更好方面具有优势,否则应始终使用字符串。For example, if you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient.例如,如果需要连接大量字符串,则附加到StringBuilder对象更有效。

Length and Capacity长度和容量

The StringBuilder class, like the String class, has a length() method that returns the length of the character sequence in the builder.StringBuilder类与String类一样,具有一个length()方法,用于返回生成器中字符序列的长度。

Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated.与字符串不同,每个字符串生成器也有一个容量,即已分配的字符空间数。The capacity, which is returned by the capacity() method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.capacity()方法返回的容量始终大于或等于长度(通常大于),并将根据需要自动扩展以适应字符串生成器的添加。

StringBuilder Constructors构造函数
Constructor构造函数 Description描述
StringBuilder() Creates an empty string builder with a capacity of 16 (16 empty elements).创建一个容量为16(16个空元素)的空字符串生成器。
StringBuilder(CharSequence cs) Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence.构造一个字符串生成器,其中包含与指定的CharSequence相同的字符,并在CharSequence后面附加16个空元素。
StringBuilder(int initCapacity) Creates an empty string builder with the specified initial capacity.创建具有指定初始容量的空字符串生成器。
StringBuilder(String s) Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.创建一个字符串生成器,该生成器的值由指定的字符串加上字符串后面额外的16个空元素初始化。

For example, the following code例如,下面的代码

// creates empty builder, capacity 16
StringBuilder sb = new StringBuilder();
// adds 9 character string at beginning
sb.append("Greetings");

will produce a string builder with a length of 9 and a capacity of 16:将生成长度为9、容量为16的字符串生成器:

A string builder's length is the number of characters it contains; a string builder's capacity is the number of character spaces that have been allocated.

The StringBuilder class has some methods related to length and capacity that the String class does not have:StringBuilder类有一些与String类没有的长度和容量相关的方法:

Length and Capacity Methods长度和容量方法
Method方法 Description描述
void setLength(int newLength) Sets the length of the character sequence.设置字符序列的长度。If newLength is less than length(), the last characters in the character sequence are truncated.如果newLength小于length(),则字符序列中的最后一个字符将被截断。If newLength is greater than length(), null characters are added at the end of the character sequence.如果newLength大于length(),则在字符序列的末尾添加空字符。
void ensureCapacity(int minCapacity) Ensures that the capacity is at least equal to the specified minimum.确保容量至少等于指定的最小值。

A number of operations (for example, append(), insert(), or setLength()) can increase the length of the character sequence in the string builder so that the resultant length() would be greater than the current capacity().许多操作(例如,append()insert()setLength())可以增加字符串生成器中字符序列的长度,从而使结果length()大于当前capacity()When this happens, the capacity is automatically increased.发生这种情况时,容量会自动增加。

StringBuilder OperationsStringBuilder操作

The principal operations on a StringBuilder that are not available in String are the append() and insert() methods, which are overloaded so as to accept data of any type.StringBuilder上在String中不可用的主要操作是append()insert()方法,它们被重载以接受任何类型的数据。Each converts its argument to a string and then appends or inserts the characters of that string to the character sequence in the string builder.每个参数都将其参数转换为字符串,然后将该字符串的字符追加或插入到字符串生成器中的字符序列中。The append method always adds these characters at the end of the existing character sequence, while the insert method adds the characters at a specified point.append方法始终在现有字符序列的末尾添加这些字符,而insert方法在指定点添加这些字符。

Here are a number of the methods of the StringBuilder class.下面是StringBuilder类的一些方法。

Various StringBuilder Methods各种StringBuilder方法
Method方法 Description描述
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)
Appends the argument to this string builder.将参数追加到此字符串生成器。The data is converted to a string before the append operation takes place.在执行追加操作之前,数据将转换为字符串。
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
The first method deletes the subsequence from start to end-1 (inclusive) in the StringBuilder's char sequence.第一个方法删除StringBuilder字符序列中从startend-1(包括)的子序列。The second method deletes the character located at index.第二种方法删除位于index处的字符。
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)
Inserts the second argument into the string builder.将第二个参数插入字符串生成器。The first integer argument indicates the index before which the data is to be inserted.第一个整数参数指示要插入数据的索引。The data is converted to a string before the insert operation takes place.在执行插入操作之前,数据将转换为字符串。
StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)
Replaces the specified character(s) in this string builder.替换此字符串生成器中的指定字符。
StringBuilder reverse() Reverses the sequence of characters in this string builder.反转此字符串生成器中的字符序列。
String toString() Returns a string that contains the character sequence in the builder.返回在生成器中包含字符序列的字符串。

Note: You can use any String method on a StringBuilder object by first converting the string builder to a string with the toString() method of the StringBuilder class.通过首先使用StringBuilder类的toString()方法将字符串生成器转换为字符串,可以在StringBuilder对象上使用任何字符串方法。Then convert the string back into a string builder using the StringBuilder(String str) constructor.然后使用StringBuilder(String str)构造函数将字符串转换回字符串生成器。

An Example一个例子

The StringDemo program that was listed in the section titled "Strings" is an example of a program that would be more efficient if a StringBuilder were used instead of a String.标题为“Strings”的部分中列出的StringDemo程序是一个示例,如果使用StringBuilder而不是字符串,则该程序的效率会更高。

StringDemo reversed a palindrome.StringDemo反转了回文。Here, once again, is its listing:这里再次列出:

public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        // put original string in an 
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 
        
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

Running the program produces this output:运行该程序会产生以下输出:

doT saw I was toD

To accomplish the string reversal, the program converts the string to an array of characters (first for loop), reverses the array into a second array (second for loop), and then converts back to a string.为了完成字符串反转,程序将字符串转换为字符数组(第一个for循环),将数组反转为第二个数组(第二个for循环),然后再转换回字符串。

If you convert the palindrome string to a string builder, you can use the reverse() method in the StringBuilder class.如果将回文字符串转换为字符串生成器,则可以在StringBuilder类中使用reverse()方法。It makes the code simpler and easier to read:它使代码更简单,更易于阅读:

public class StringBuilderDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
         
        StringBuilder sb = new StringBuilder(palindrome);
        
        sb.reverse();  // reverse it
        
        System.out.println(sb);
    }
}

Running this program produces the same output:运行此程序会产生相同的输出:

doT saw I was toD

Note that println() prints a string builder, as in:请注意,println()打印字符串生成器,如中所示:

System.out.println(sb);

because sb.toString() is called implicitly, as it is with any other object in a println() invocation.因为sb.toString()是隐式调用的,就像println()调用中的任何其他对象一样。


Note: There is also a StringBuffer class that is exactly the same as the StringBuilder class, except that it is thread-safe by virtue of having its methods synchronized.还有一个StringBuffer类与StringBuilder类完全相同,只是它通过同步其方法而具有线程安全性。Threads will be discussed in the lesson on concurrency.线程将在“并发性”课程中讨论。

Previous page: Comparing Strings and Portions of Strings
Next page: Summary of Characters and Strings