อ่านไฟล์ -> แยกคำด้วย Space -> วนลูป: ถ้าเป็นคำที่ต้องการเก็บ -> เก็บไว้, ไม่ใช่ -> แทนที่ทุกตัวอักษรด้วย # -> รวมกลับ
ตัวอย่างโค้ด
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ReplaceExceptWord {
public static String fileToString(String filePath) throws FileNotFoundException {
StringBuilder sb = new StringBuilder();
try (Scanner sc = new Scanner(new File(filePath))) {
while (sc.hasNextLine()) {
sb.append(sc.nextLine()).append(System.lineSeparator());
}
}
return sb.toString();
}
public static void main(String[] args) throws FileNotFoundException {
String contents = fileToString("D:/input.txt");
System.out.println("Original:\n" + contents);
// แยกคำด้วย Space
String[] words = contents.split(" ");
System.out.println("Words: " + Arrays.toString(words));
StringBuilder result = new StringBuilder();
String protectWord = "Tutorialspoint"; // คำที่อยากเก็บไว้
for (int i = 0; i < words.length; i++) {
if (words[i].equals(protectWord)) {
result.append(words[i]);
} else {
// แทนที่ทุก Character ด้วย # (Regex . = any char)
result.append(words[i].replaceAll(".", "#"));
}
if (i < words.length - 1) result.append(" "); // คั่น Space
}
System.out.println("Result:\n" + result);
}
}
ผลลัพธ์
Original: Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free. Words: [Hello, how, are, you, welcome, to, Tutorialspoint, we, provide, hundreds, of, technical, tutorials, for, free.] Result: ##### ### ### ### ####### ## Tutorialspoint ## ####### ######### ## ######### ######### ### ####.
คำอธิบาย
split(" ")- แยกคำด้วย Space (Simple)replaceAll(".", "#")- Regex.Match ทุก Character เดียว -> แทนที่ทั้งคำด้วย #- เก็บคำ
protectWordไว้ตามเดิม
ปรับปรุง: รองรับ Punctuation และ Case-Insensitive
// แยกคำรักษา Punctuation (ใช้ Regex Word Boundary)
String[] words = contents.split("(?=\\s)|(?<=\\s)"); // Complex
// หรือใช้ Pattern Matcher สำหรับ Replace ทั้งคำยกเว้นคำหนึ่ง
String regex = "\\b(?!Tutorialspoint\\b)\\w+\\b"; // Word ที่ไม่ใช่ Tutorialspoint
String result = contents.replaceAll(regex, m -> "#".repeat(m.group().length()));
// Java 11+ repeat(), Lambda ใน replaceAll (ต้องใช้ Matcher แทน)
Java 9+ ใช้ Matcher.replaceAll(Function)
import java.util.regex.*;
public class AdvancedReplace {
public static void main(String[] args) {
String text = "Hello Tutorialspoint World";
Pattern p = Pattern.compile("\\b(?!Tutorialspoint\\b)\\w+\\b");
Matcher m = p.matcher(text);
String result = m.replaceAll(match -> "#".repeat(match.group().length()));
System.out.println(result); // ##### Tutorialspoint #####
}
}
สรุป
วิธีพื้นฐาน: Split ด้วย Space -> Loop ตรวจสอบคำ -> ReplaceAll("." , "#") -> Join กลับ สำหรับ Production ควรใช้ Regex Word Boundary (\b) และ Matcher.replaceAll() เพื่อรองรับ Punctuation และ Case ได้ดีกว่า