Java StringBuilder trimToSize() 方法



Java StringBuilder trimToSize() 方法用於調整 StringBuilder 物件的字元序列的容量。簡而言之,它嘗試減少字元序列使用的儲存空間。

在 Java 中,trim() 是一個內建方法,通常用於刪除或修剪給定序列或字串的空格

trimToSize() 不接受任何引數,該方法不丟擲任何異常。它不返回任何值。

語法

以下是Java StringBuilder trimToSize() 方法的語法:

public void trimToSize()

引數

  • 它不接受任何引數。

返回值

此方法不返回任何值。

示例:根據 StringBuilder 的容量修剪字串的大小

如果 StringBuilder 物件的值不為空,則 trimToSize() 方法會減小給定序列的容量。

在下面的示例中,我們使用“Hello World”的值例項化StringBuilder 類。使用trimToSize() 方法,我們嘗試減少 StringBuilder 物件的字元序列的容量。

public class TrimSize {
   public static void main(String[] args) {
      //create an object of the StringBuilder class
      StringBuilder sb = new StringBuilder("Hello World");
      System.out.println("StringBuilder: " + sb);
      //get the capacity and length
      System.out.println("The length of the sequence: " + sb.length());
      System.out.println("The sequence capacity before trim: " + sb.capacity());
      //using the trimToSize() method
      sb.trimToSize();
      System.out.println("The sequence capacity after trim: " + sb.capacity());
   }
}

輸出

執行上述程式後,將產生以下結果:

StringBuilder: Hello World
The length of the sequence: 11
The sequence capacity before trim: 27
The sequence capacity after trim: 11

示例:根據 StringBuilder 的容量修剪字串的大小

在下面的示例中,我們建立了一個值為“Tutorials Point”StringBuilder 類物件。然後,使用append() 方法,我們將“India”值追加到其中。使用trimToSize() 方法,我們嘗試減小其容量。

public class StringBuilderDemo {
   public static void main(String[] args) {
      //create an object of the StringBuilder class
      StringBuilder sb = new StringBuilder("Tutorials Point ");
      System.out.println("StringBuilder: " + sb);
      // append the string to StringBuilder
      sb.append("India");
      //By using trimToSize() method is to trim the sb object
      sb.trimToSize();
      System.out.println("After trim the object: " + sb);
   }
}

輸出

以下是上述程式的輸出:

StringBuilder: Tutorials Point 
After trim the object: Tutorials Point India
java_lang_stringbuilder.htm
廣告