Java程式用於替換句子中的單詞為星號


在本文中,我們將學習如何使用Java替換句子中特定單詞為星號。此技術可用於出於隱私或審查目的而模糊文字中的某些單詞。

問題陳述

開發一個Java程式,該程式接收一個句子和一個要審查的單詞作為輸入,然後輸出用星號替換指定單詞的句子,同時保留句子的原始格式。

輸入

This is a sample only, the sky is blue, water is transparent

輸出

This is a ****** only, the sky is blue, water is transparent

用星號替換句子中單詞的步驟

  • 開始。
  • 定義一個函式replace_word,該函式接收一個句子和一個目標單詞。
  • 使用正則表示式根據空格將句子拆分為單詞陣列。
  • 建立一個與要替換的單詞長度相同的星號字串。
  • 使用for迴圈遍歷單詞陣列,將目標單詞的任何出現替換為星號字串。
  • 將單詞組合回單個字串,保持原始間距。
  • 將修改後的句子列印到控制檯。
  • 結束

Java程式用於替換句子中的單詞為星號

要替換句子中的單詞為星號,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的函式,該函式將句子和模式作為引數。句子被拆分並存儲在字串陣列中。定義一個空字串,並根據其長度迭代模式。星號值定義為*,對於句子中的每個字元,將字元與模式進行比較,並將特定出現替換為星號符號。最終字串顯示在控制檯上。

更新於: 2024年7月24日

2K+ 閱讀量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.