如何在 Java 中修剪 StringBuffer 中的空格?


Java 的 String 類(java.lang 包的一部分)表示一組字元。Java 程式中的所有字串字面量,例如“abc”,都作為此類的例項實現。字串物件是不可變的,一旦建立了字串物件,就無法更改其值。如果嘗試這樣做,則不會更改值,而是會建立一個具有所需值的新物件,並且引用會轉移到新建立的物件,留下先前未使用的物件。

當需要對字串進行大量修改時,可以使用 StringBuffer(和 StringBuilder)類。

與字串不同,StringBuffer 型別的物件可以反覆修改,而不會留下大量新的未使用的物件。它是一個執行緒安全的、可變的字元序列。

示例

 線上演示

public class StringBufferExample {
   public static void main(String[] args) {
      StringBuffer buffer = new StringBuffer();
      buffer.append("Hello ");
      buffer.append("how ");
      buffer.append("are ");
      buffer.append("you");
      System.out.println("Contents of the string buffer: "+buffer);
   }
}

輸出

Contents of the string buffer: Hello how are you

修剪空格

StringBuffer() 沒有提供任何方法來刪除其內容之間的空格。

String 類的 trim() 方法首先複製當前字串,刪除其開頭和結尾的空格,然後返回它。

要在 StringBuffer 中刪除開頭和結尾的空格 -

  • 您需要使用 toString() 方法將 StringBuffer 物件轉換為 String 物件。

  • 對結果呼叫 trim() 方法。

示例

 線上演示

public class StringBufferCapacity {
   public static void main(String[] args) {
      StringBuffer buffer = new StringBuffer();
      buffer.append(" Hello ");
      buffer.append("how ");
      buffer.append("are ");
      buffer.append("you ");
      System.out.println("Contents of the string buffer: "+buffer);
      //Converting StringBuffer to String
      String str = buffer.toString();
      //Removing the leading and trailing spaces
      System.out.println(str.trim());
   }
}

輸出

Contents of the string buffer: Hello how are you

如果要完全刪除 StringBuffer 中的空格,一種方法是 -

  • 刪除其開頭和結尾的零。

  • 使用 toString() 方法將 StringBuffer 物件轉換為 String 值。

  • String 類的 split() 方法接受分隔符(以 String 格式),根據給定的分隔符將給定字串拆分為字串陣列。

    使用此方法拆分上一步中獲得的字串。

  • 將陣列中每個元素追加到另一個 StringBuffer。

示例

 線上演示

public class StringBufferCapacity {
   public static void main(String[] args) {
      StringBuffer buffer = new StringBuffer();
      buffer.append(" Hello ");
      buffer.append("how ");
      buffer.append("are ");
      buffer.append("you ");
      System.out.println("Contents of the string buffer: "+buffer);
      //Converting StringBuffer to String
      String str = buffer.toString();
      //Removing the leading and trailing spaces
      str = str.trim();
      //Splitting the String
      String array[] = str.split(" ");
      //Appending each value to a buffer
      StringBuffer result = new StringBuffer();
      for(int i=0; i<array.length; i++) {
         result.append(array[i]);
      }
      System.out.println("Result: "+result);
   }
}

輸出

Contents of the string buffer: Hello how are you
Result: Hellohowareyou

更新於: 2019年9月10日

2K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.