Java StringBuilder

Java StringBuilder class is mutable sequence of characters. StringBuilder Class can be comparable to String however the StringBuilder class provides more versatility because of its modification features.

Java StringBuilder类是可变的字符序列。 StringBuilder类可以与String相提并论,但是StringBuilder类由于其修改功能而提供了更多的通用性。

Java StringBuilder (Java StringBuilder)

  • StringBuilder class provides an API similar to StringBuffer, but unlike StringBuffer, it doesn’t guarantee thread safety.

    StringBuilder类提供类似于StringBuffer的API,但是与StringBuffer不同,它不能保证线程安全。
  • Java StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case).

    Java StringBuilder类设计用于在单个线程正在使用字符串缓冲区的地方(通常是这种情况)代替StringBuffer。
  • If execution speed and performance is a factor, StringBuilder class can be used in place of StringBuffer.

    如果执行速度和性能是一个因素,则可以使用StringBuilder类代替StringBuffer。
  • The bread-and-butter operations provided by the StringBuilder Class are the append() and insert() methods. These methods are overloaded within StringBuilder in order to accommodate different data type.

    StringBuilder类提供的基本操作是append()insert()方法。 为了容纳不同的数据类型,这些方法在StringBuilder中被重载。
  • The general process flow of StringBuilder append and insert methods is: (1) converts a given data to a string then (2) appends or inserts the characters of that string to the string builder. Java StringBuilder append() method always adds these characters at the end of the builder; insert() method inserts character(s) at a specified point.

    StringBuilder追加和插入方法的一般处理流程是:(1)将给定的数据转换为字符串,然后(2)将该字符串的字符追加或插入到字符串生成器。 Java StringBuilder append()方法始终将这些字符添加到生成器的末尾。 insert()方法在指定点插入字符。

StringBuilder类图 (StringBuilder Class Diagram)

StringBuffer和StringBuilder (StringBuffer and StringBuilder)

StringBufferStringBuilder
Synchronized, hence thread safe.Not synchronized, not thread safe.
Operates slower due to thread safety featureBetter performance compared to StringBuffer
Has some extra methods – substring, length, capacity etc.Not needed because these methods are present in String too.
Introduced in Java 1.2Introduced in Java 1.5 for better performance.
StringBuffer StringBuilder
同步,因此线程安全。 不同步,线程不安全。
由于具有线程安全功能,因此运行速度较慢 与StringBuffer相比,性能更好
有一些额外的方法–子字符串,长度,容量等。 不需要,因为这些方法也存在于String中。
在Java 1.2中引入 在Java 1.5中引入了更高的性能。

Java StringBuilder构造函数 (Java StringBuilder Constructors)

ConstructorDescription
StringBuilder()Creates an empty string builder with a default capacity of 16 (16 empty elements).
StringBuilder(CharSequence cs)Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence.
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.
建设者 描述
StringBuilder() 创建一个默认容量为16(16个空元素)的空字符串生成器。
StringBuilder(CharSequence CS) 构造一个字符串生成器,其中包含与指定CharSequence相同的字符,以及在CharSequence后面附加的16个空元素。
StringBuilder(int initCapacity) 创建具有指定初始容量的空字符串构建器。
StringBuilder(String s) 创建一个字符串生成器,其值由指定的字符串初始化,并在该字符串后附加16个空元素。

StringBuilder的长度和容量 (StringBuilder Length and Capacity)

Java StringBuilder class, much like the String class, has length() method that returns the length of the character sequence in the builder.

Java StringBuilder类与String类非常相似,具有length()方法,该方法返回构建器中字符序列的长度。

However, StringBuilder inherits capacity() method from its superclass AbstractStringBuilder, that returns the number of character spaces that have been allocated. The returned value is always greater than or equal to the length (usually greater than) and automatically expands whenever necessary to accommodate character additions to the string builder.

但是,StringBuilder从其超类AbstractStringBuilder继承了Capacity capacity()方法,该方法返回已分配的字符空间的数量。 返回的值始终大于或等于长度(通常大于),并在需要时自动扩展以适应向字符串生成器添加字符。

// creates empty builder, capacity 16
StringBuilder sb = new StringBuilder();

// adds 5 character string at beginning
sb.append("Hello");

System.out.println("StringBuilder length = "+sb.length()); // prints 5
System.out.println("StringBuilder capacity = "+sb.capacity()); // prints 16

There are couple of other methods related to StringBuilder length and capacity.

还有其他几种与StringBuilder的长度和容量有关的方法。

  1. 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. If newLength is greater than length(), null characters are added at the end of the character sequence.

    void setLength(int newLength) :设置字符序列的长度。 如果newLength小于length(),则字符序列中的最后一个字符将被截断。 如果newLength大于length(),则在字符序列的末尾添加空字符。
  2. void ensureCapacity(int minCapacity): Ensures that the capacity is at least equal to the specified minimum.

    void ensureCapacity(int minCapacity) :确保容量至少等于指定的最小值。

StringBuilder methods like append(), insert() or setLength() can increase the length of the character sequence in the string builder so that the returned value of length() would be greater than the current capacity(). In this case, the capacity is automatically increased.

诸如append()insert()setLength()类的StringBuilder方法可以增加字符串生成器中字符序列的长度,以便返回的length()值大于当前的Capacity()。 在这种情况下,容量会自动增加。

Java StringBuilder示例 (Java StringBuilder Example)

Let’s see the examples of different methods of StringBuilder class.

让我们看一下StringBuilder类的不同方法的示例。

  1. append(): The StringBuilder append() method concatenates or attaches the passed String argument with the existing declared string. It attaches it after the declared string.
    package com.journaldev.java;
    
    public class StringBuilderExample {
    
    	public static void main(String[] args) {
    		
    		StringBuilder sb = new StringBuilder("Hello ");
    		sb.append("World");// now original string is changed
    		System.out.println(sb);// prints Hello World
    
    	}
    
    }

    Output: Hello World

    append() :StringBuilder append()方法将传递的String参数与现有声明的字符串连接或附加。 它将其附加在声明的字符串之后。

    输出 :Hello World

  2. insert(): StringBuilder insert() method inserts the passed String argument at the passed String index.
    StringBuilder sb = new StringBuilder("HellWorld");
    
    sb.insert(4, "o ");
    System.out.println(sb);// prints Hello World

    insert() :StringBuilder insert()方法将通过的String参数插入到通过的String索引处。
  3. replace(int startIndex, int endIndex, String str): StringBuilder replace() method replaces the existing declared string. String replacement occurs from the passed startingIndex up to the endingIndex.
    StringBuilder sb = new StringBuilder("Hello World!");
    		
    sb.replace(6,11,"Earth");
    
    System.out.println(sb);// prints Hello Earth!

    replace(int startIndex, int endIndex, String str) :StringBuilder replace()方法替换现有已声明的字符串。 字符串替换发生在从传递的startingIndex到EndingIndex的范围内。
  4. delete(int startIndex, int endIndex): StringBuilder delete() method deletes a character or sets of characters. Deletion occurs at passed startingIndex up to endingIndex.
    StringBuilder sb = new StringBuilder("JournalDev.com");
    		
    sb.delete(7,14);
    		
    System.out.println(sb);// prints Journal

    delete(int startIndex, int endIndex) :StringBuilder delete()方法删除一个字符或一组字符。 删除发生在传递的startingIndex到endingIndex之间。
  5. reverse(): The reverse() method of StringBuilder class reverses the existing declared string. Invoking a reverse() method on a StringBuilder object with no existing declared value throws NullPointerException.
    StringBuilder sb = new StringBuilder("lived");
    		
    sb.reverse();
    		
    System.out.println(sb);// prints devil

    reverse() :StringBuilder类的reverse()方法将反转现有的声明字符串。 在没有现有声明值的StringBuilder对象上调用reverse()方法将引发NullPointerException
  6. capacity(): The capacity() method of StringBuilder class returns the current capacity of the StringBuilder object. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (old_capacity*2)+2 e.g. at current capacity 16, it becomes (16*2)+2=34.
    StringBuilder sb=new StringBuilder();  
    
    System.out.println(sb.capacity()); // default value 16  
    
    sb.append("Java");  
    System.out.println(sb.capacity()); // still 16  
    
    sb.append("Hello StringBuilder Class!");
    System.out.println(sb.capacity()); // (16*2)+2

    capacity() :StringBuilder类的Capacity()方法返回StringBuilder对象的当前容量。 生成器的默认容量为16。如果字符数从其当前容量增加,则其容量将增加(old_capacity * 2)+2,例如,在当前容量为16时,它将变为(16 * 2)+ 2 = 34。
  7. ensureCapacity(): The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (old_capacity*2)+2 e.g. at current capacity 16, it becomes (16*2)+2 which is 34.
    package com.journaldev.java;
    
    public class StringBuilderExample {
    
    	public static void main(String[] args) {
    		
    		StringBuilder sbObj=new StringBuilder();  
    		System.out.println(sbObj.capacity());//default 16 
    		
    		sbObj.append("Java StringBuilder Class!");  
    		System.out.println(sbObj.capacity());// capacity 34	
    
    		sbObj.ensureCapacity(12);// no change  
    		System.out.println(sbObj.capacity());//still 34  
    
    		sbObj.ensureCapacity(60); // (34*2)+2 = 70 
    		System.out.println(sbObj.capacity()); //70 
    
    	}
    
    }

    ensureCapacity() :StringBuilder类的ensureCapacity()方法可确保给定容量为当前容量的最小值。 如果大于当前容量,则将容量增加(old_capacity * 2)+2,例如,在当前容量16时,它将变为(16 * 2)+2,即34。

That’s all for Java StringBuilder class. It’s a very useful class to work with Strings in java.

Java StringBuilder类就这些了。 在Java中使用Strings是一个非常有用的类。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16833/java-stringbuilder

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值