如何用Java中的另一個單詞替換字串中出現的任何單詞?


String類的replaceAll()方法接受兩個字串,一個代表查詢字串的正則表示式,另一個代表替換字串。

並且,用給定的字串替換所有匹配的序列。因此,要在字串中用另一個單詞替換某個特定單詞-

  • 獲取所需的字串。

  • 透過傳遞表示要替換的單詞(在單詞邊界“\b”內)的正則表示式和替換字串作為引數,對所得字串呼叫replaceAll方法。

  • 檢索結果並列印。

示例

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReplacingWords {
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(new File("D://sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append("
"+input);       }       String contents = sb.toString();       System.out.println("Contents of the string: "+contents);       contents = contents.replaceAll("\bTutorials point\b", "TP");       System.out.println("Contents of the string after replacement: ");       System.out.println(contents);    } }

輸出

Contents of the string:
Tutorials point originated from the idea that there exists a class of readers who respond better to on-line content
and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
At Tutorials point we provide high quality learning-aids for free of cost.
Tutorials point recently developed an app to help students from 6th to 12th.
Contents of the string after replacement:
TP originated from the idea that there exists a class of readers who respond better to on-line content
and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
At TP we provide high quality learning-aids for free of cost.
TP recently developed an app to help students from 6th to 12th.

更新於:2019年10月10日

1K+瀏覽量

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.