首頁  >  文章  >  Java  >  在Java中編寫一個程序,將文件中的所有字元替換為“#”,除了特定的單字

在Java中編寫一個程序,將文件中的所有字元替換為“#”,除了特定的單字

WBOY
WBOY轉載
2023-09-13 08:57:17936瀏覽

在Java中編寫一個程序,將文件中的所有字元替換為“#”,除了特定的單字

String類別的split()方法。將目前字串拆分為給定正規表示式的匹配項。此方法傳回的陣列包含此字串的每個子字串,該子字串由與給定表達式匹配的另一個子字串終止或以字串末尾終止。

replaceAll() String 類別的方法接受兩個表示正規表示式的字串和一個替換字串,並用給定的字串替換匹配的值。

以「#」取代檔案中除特定單字之外的所有字元(一種方式)-

  • #將檔案的內容讀取到字串中。

  • 建立一個空的StringBuffer 物件。

  • 使用 split() 方法將取得的字串拆分為 String 陣列。

  • 遍歷得到的陣列。

  • 如果其中有任何元素與所需的單字匹配,則將其追加到 String 緩衝區。

  • 將剩餘單字中的所有字元替換為“#”,並將其追加到 StringBuffer 物件中。

  • 最後將 StingBuffer 轉換為 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 ############################################

以上是在Java中編寫一個程序,將文件中的所有字元替換為“#”,除了特定的單字的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除