Java程式:替換檔案中除特定單詞外的所有字元為 '#'


String類的**split()**方法根據給定的正則表示式將當前字串分割成多個子字串。此方法返回的陣列包含此字串的每個子字串,這些子字串以與給定表示式匹配的另一個子字串結尾,或者以字串結尾。

String類的**replaceAll()**方法接受兩個字串,分別表示正則表示式和替換字串,並將匹配的值替換為給定的字串。

替換檔案中除特定單詞外的所有字元為 '#'(一種方法):

  • 將檔案內容讀取到一個字串中。

  • 建立一個空的StringBuffer物件。

  • 使用**split()**方法將獲得的字串分割成字串陣列。

  • 遍歷獲得的陣列。

  • 如果其中的任何元素與所需的單詞匹配,則將其新增到StringBuffer中。

  • 將所有其餘單詞中的字元替換為“#”,並將它們新增到StringBuffer物件中。

  • 最後將StringBuffer轉換為String。

示例

假設我們有一個名為sample.txt的檔案,其內容如下:

Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free.

以下程式將檔案內容讀取到字串中,並將其中除特定單詞外的所有字元替換為 '#'。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ReplaceExcept {
   public static String fileToString() throws FileNotFoundException {
      String filePath = "D://input.txt";
      Scanner sc = new Scanner(new File(filePath));
      StringBuffer sb = new StringBuffer();
      String input;
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      return sb.toString();
   }
   public static void main(String args[]) throws FileNotFoundException {
      String contents = fileToString();
      System.out.println("Contents of the file: \n"+contents);
      //Splitting the words
      String strArray[] = contents.split(" ");
      System.out.println(Arrays.toString(strArray));
      StringBuffer buffer = new StringBuffer();
      String word = "Tutorialspoint";
      for(int i = 0; i < strArray.length; i++) {
         if(strArray[i].equals(word)) {
            buffer.append(strArray[i]+" ");
         } else {
            buffer.append(strArray[i].replaceAll(".", "#"));
         }
      }
      String result = buffer.toString();
      System.out.println(result);
   }
}

輸出

Contents of the file:
Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free.
[Hello, how, are, you, welcome, to, Tutorialspoint, we, provide, hundreds, of, technical, tutorials, for, free.]
#######################Tutorialspoint ############################################

更新於:2019年10月14日

525 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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