拼接 (concat())、替換 (replace()) 和修整 (trim()) Java 中的字串。


String 類中的 concat() 方法將一個 String 追加到另一個 String 的末尾。該方法返回一個 String,其值為此方法傳遞的 String 本身,附加到呼叫該方法的 String 的末尾。

示例

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

更新於: 2020 年 2 月 26 日

1K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.