> Java > java지도 시간 > 본문

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

WBOY
풀어 주다: 2023-09-13 08:57:17
앞으로
954명이 탐색했습니다.

특정 단어를 제외하고 파일의 모든 문자를 #으로 바꾸는 프로그램을 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으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!