Java
 Computer >> コンピューター >  >> プログラミング >> Java

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


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

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

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

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

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

  • split()を使用して、取得した文字列を文字列の配列に分割します メソッド。

  • 得られた配列をトラバースします。

  • その中のいずれかの要素が必要な単語に一致する場合は、それを文字列バッファに追加します。

  • 残りのすべての単語の文字を「#」に置き換えて、StringBufferオブジェクトに追加します。

  • 最後に、StingBufferを文字列に変換します。

次の内容の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 ############################################

  1. ディレクトリ内のすべてのファイルを再帰的に削除するJavaプログラム(ファイルのみ)

    ディレクトリDにExampleDirectoryという名前のフォルダがあり、7つのファイルと2つのディレクトリが-であると仮定します。 どこで、 SampleDirectory1には、SampleFile1.txtとSampleFile2.txtという名前の2つのファイルが含まれています。 SampleDirectory2には、SampleFile2.txtとSampleFile3.txtという名前の2つのファイルが含まれています。 例 次のJavaの例では、 ExampleDirectoryという名前のディレクトリ内のすべてのファイルを削除します。 。 impo

  2. 文字列内の「a」のすべての出現箇所を$に置き換えるPythonプログラム

    文字列内で出現するすべての「a」を「$」などの文字に置き換える必要がある場合は、文字列を繰り返して、「+=」演算子を使用して置き換えることができます。 以下は同じのデモンストレーションです- 例 my_str = "Jane Will Rob Harry Fanch Dave Nancy" changed_str = '' for char in range(0, len(my_str)):    if(my_str[char] == 'a'):       changed_str +=