Để thay thế từ bằng dấu hoa thị trong câu, chương trình Java như sau:
Ví dụ
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)); } }
Kết quả
This is a ****** only, the sky is blue, water is transparent
Lớp Demo chứa hàm replace_word nhận câu và mẫu làm tham số. Câu được tách và lưu trong mảng chuỗi. Chuỗi rỗng định nghĩa, mẫu lặp qua theo độ dài. Giá trị dấu hoa thị định nghĩa là * và với mỗi ký tự trong câu, ký tự so sánh với mẫu và xuất hiện cụ thể được thay thế bằng dấu hoa thị. Chuỗi cuối cùng hiển thị trên console.