>  기사  >  Java  >  특정 단어를 제외하고 파일의 모든 문자를 "#"으로 바꾸는 프로그램을 Java로 작성하십시오.

특정 단어를 제외하고 파일의 모든 문자를 "#"으로 바꾸는 프로그램을 Java로 작성하십시오.

WBOY
WBOY앞으로
2023-09-13 08:57:17933검색

특정 단어를 제외하고 파일의 모든 문자를 #으로 바꾸는 프로그램을 Java로 작성하십시오.

String 클래스의 split() 메소드. 현재 문자열을 주어진 정규식과 일치하는 항목으로 분할합니다. 이 메서드에서 반환된 배열에는 지정된 표현식과 일치하는 다른 하위 문자열로 끝나거나 문자열 끝에서 끝나는 이 문자열의 각 하위 문자열이 포함되어 있습니다.

replaceAll() String 클래스의 메서드는 정규식을 나타내는 두 개의 문자열과 대체 문자열을 받아들이고 일치하는 값을 주어진 문자열로 바꿉니다.

특정 단어를 제외한 파일의 모든 문자를 "#"(단방향)으로 바꿉니다. -

  • 파일 내용을 문자열로 읽어옵니다.

  • 빈 StringBuffer 개체를 만듭니다.

  • 얻은 문자열을 문자열 배열로 분할하려면 split() 메서드를 사용하세요.

  • 얻은 배열을 탐색합니다.

  • 원하는 단어와 일치하는 요소가 있으면 문자열 버퍼에 추가하세요.

  • 나머지 단어의 모든 문자를 "#"으로 바꾸고 이를 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으로 문의하시기 바랍니다. 삭제