ในการแทนที่คำด้วยเครื่องหมายดอกจันในประโยค โปรแกรม Java มีดังต่อไปนี้ −
ตัวอย่าง
public class Demo{
static String replace_word(String sentence, String pattern){
String[] word_list = sentence.split("\\s+");
String my_result = "";
String asterisk_val = "";
for (int i = 0; i < pattern.length(); i++)
asterisk_val += '*';
int my_index = 0;
for (String i : word_list){
if (i.compareTo(pattern) == 0)
word_list[my_index] = asterisk_val;
my_index++;
}
for (String i : word_list)
my_result += i + ' ';
return my_result;
}
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(replace_word(sentence, pattern));
}
} ผลลัพธ์
This is a ****** only, the sky is blue, water is transparent
คลาสที่ชื่อว่า Demo มีฟังก์ชันชื่อ 'replace_word' ที่ใช้ประโยคและรูปแบบเป็นพารามิเตอร์ ประโยคถูกแยกและเก็บไว้ในอาร์เรย์สตริง มีการกำหนดสตริงว่าง และรูปแบบจะวนซ้ำตามความยาว
ค่าดอกจันถูกกำหนดเป็น '*' และสำหรับอักขระทุกตัวในประโยค อักขระจะถูกนำไปเปรียบเทียบกับรูปแบบ และเฉพาะการเกิดขึ้นจะถูกแทนที่ด้วยสัญลักษณ์ดอกจัน สตริงสุดท้ายจะแสดงบนคอนโซล