Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình thay thế tất cả ký tự trong file bằng '#' trừ một từ cụ thể trong Java

Yêu cầu: Đọc file, giữ nguyên 1 từ khóa, thay tất cả ký tự còn lại bằng #.

Thuật toán

  1. Đọc toàn file thành String.
  2. Tách từ bằng split(" ") (theo space).
  3. Duyệt mảng từ: nếu từ == từ khóa → giữ nguyên; ngược lại → replaceAll(".", "#").
  4. Ghép lại kết quả.

Ví dụ minh họa

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class ReplaceExceptWord {
    public static String fileToString() throws FileNotFoundException {
        Scanner sc = new Scanner(new File("D://input.txt"));
        StringBuilder sb = new StringBuilder();
        while (sc.hasNextLine()) {
            sb.append(sc.nextLine());
        }
        sc.close();
        return sb.toString();
    }
    
    public static void main(String args[]) throws FileNotFoundException {
        String contents = fileToString();
        System.out.println("Nội dung gốc:\n" + contents);
        
        // Tách từ (theo space)
        String[] words = contents.split(" ");
        System.out.println("Từ tách được: " + Arrays.toString(words));
        
        StringBuilder result = new StringBuilder();
        String keyword = "Tutorialspoint";
        
        for (String word : words) {
            if (word.equals(keyword)) {
                result.append(word).append(" ");
            } else {
                result.append(word.replaceAll(".", "#")).append(" ");
            }
        }
        
        System.out.println("Kết quả:\n" + result.toString().trim());
    }
}

Kết quả

Nội dung gốc:
Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free.

Từ tách được: [Hello, how, are, you, welcome, to, Tutorialspoint, we, provide, hundreds, of, technical, tutorials, for, free.]

Kết quả:
####### ### ### ### ####### ## Tutorialspoint ## ####### ######### ## ######### ######### ### ####.

Cải tiến: Giữ nguyên khoảng trắng, xuống dòng

Dùng regex \\b(Tutorialspoint)\\b|. với replaceAll và lambda (Java 9+):

String result = contents.replaceAll("\\bTutorialspoint\\b|.", m -> 
    m.group(1) != null ? m.group(1) : "#"
);

Lưu ý: Cách split(" ") mất xuống dòng, nhiều space. Cách regex tốt hơn cho format phức tạp.