Java Program to replace a word with asterisks in a sentence

To replace a word with asterisks in a sentence, the Java program is as follows −


 Live Demo

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;
      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

A class named Demo contains a function named ‘replace_word’ that takes the sentence and the pattern as parameters. A sentence is split and stored in a string array. An empty string is defined, and the pattern is iterated over, based on its length.

An asterisk value is defined as ‘*’ and for every character in the sentence, the character is compared to the pattern and a specific occurrence is replaced with the asterisk symbol. The final string is displayed on the console.

Updated on: 13-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started