Java String,Java StringBuilder

 2023-11-19 阅读 26 评论 0

摘要: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類是可變的字符序列。 StringBuilde

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()方法,該方法返回構建器中字符序列的長度。

Java String,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.

toString。 諸如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 changedSystem.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。

java中stringbuilder用法、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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/183190.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息