concat()、replace() 和 trim() Java 字串。


String 類的 concat() 方法將一個字串追加到另一個字串的末尾。該方法返回一個字串,其中包含傳遞給該方法以及用於呼叫此方法的字串末尾附加的字串的值。

示例

public class Test {
   public static void main(String args[]) {
      String s = "Strings are immutable";
      s = s.concat(" all the time");
      System.out.println(s);
   }
}

輸出

Strings are immutable all the time

String 類的 replace() 方法會返回一個新字串,該字串是由將該字串中所有出現的 oldChar 替換為 newChar 而產生的。

示例

public class Test {
   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      System.out.print("Return Value :" );
      System.out.println(Str.replace('o', 'T'));
      System.out.print("Return Value :" );
      System.out.println(Str.replace('l', 'D'));
   }
}

輸出

Return Value :WelcTme tT TutTrialspTint.cTm
Return Value :WeDcome to TutoriaDspoint.com

String 類的 trim() 方法會返回一個字串的副本,其中已省略前導和尾隨空白。

示例

import java.io.*;
public class Test {
   public static void main(String args[]) {
      String Str = new String(" Welcome to Tutorialspoint.com ");
      System.out.print("Return Value :" );
      System.out.println(Str.trim() );
   }
}

輸出

Return Value :Welcome to Tutorialspoint.com

更新於: 26-2-2020

超過 1K 瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告