ファイル内の特定の単語を除くすべての文字を「#」に置き換えるプログラムを Java で作成します

WBOY
リリース: 2023-09-13 08:57:17
転載
953 人が閲覧しました

ファイル内の特定の単語を除くすべての文字を「#」に置き換えるプログラムを Java で作成します

split() String クラスのメソッド。現在の文字列を、指定された正規表現に一致するものに分割します。このメソッドによって返される配列には、指定された式に一致する別の部分文字列で終了するか、文字列の最後で終了するこの文字列の各部分文字列が含まれます。

replaceAll() String クラスのメソッドは、正規表現を表す 2 つの文字列と置換文字列を受け入れ、一致する値を指定された文字列で置き換えます。

特定の単語を除くファイル内のすべての文字を「#」に置き換えます (一方向) -

  • ファイルの内容を文字列に読み取ります。

  • 空の StringBuffer オブジェクトを作成します。

  • split() メソッドを使用して、取得した文字列を 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 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!