โจทย์: หาคำที่ตรงกับ pattern แล้วแทนที่ด้วย * ตามความยาวคำ
ตัวอย่างโค้ด (ปรับปรุง)
public class Demo {
public static String replaceWord(String sentence, String target) {
if (sentence == null || target == null || target.isEmpty()) {
return sentence;
}
// สร้าง asterisks ตามความยาว target
String asterisks = "*".repeat(target.length()); // Java 11+
// String asterisks = new String(new char[target.length()]).replace('\0', '*'); // Java 10-
// Split ด้วย regex รองรับ whitespace หลายตัว
String[] words = sentence.split("\\s+");
for (int i = 0; i < words.length; i++) {
if (words[i].equals(target)) {
words[i] = asterisks;
}
}
return String.join(" ", words);
}
public static void main(String[] args) {
String sentence = "This is a sample only, the sky is blue, water is transparent";
String pattern = "sample";
System.out.println("Original: " + sentence);
System.out.println("Replaced: " + replaceWord(sentence, pattern));
}
}
ผลลัพธ์
Original: This is a sample only, the sky is blue, water is transparent
Replaced: This is a ****** only, the sky is blue, water is transparent
ข้อควรพิจารณา
- Case sensitivity: ใช้
equalsIgnoreCase() ถ้าต้องการไม่สนใจพิมพ์เล็ก/ใหญ่
- Word boundaries: โค้ดนี้ split ด้วย whitespace คำที่มี punctuation (sample,) จะไม่ match → ใช้ regex
\\b สำหรับ word boundary จริง
- Regex version:
sentence.replaceAll("\\b" + Pattern.quote(target) + "\\b", asterisks)
Regex Version (แนะนำ)
public static String replaceWordRegex(String sentence, String target) {
if (sentence == null || target == null || target.isEmpty()) return sentence;
String asterisks = "*".repeat(target.length());
String pattern = "\\b" + Pattern.quote(target) + "\\b";
return sentence.replaceAll(pattern, asterisks);
}