
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace a Word with Asterisks in a Sentence in Java
In this article, we will learn how to replace a specific word in a sentence with asterisks using Java. This technique can be useful for obscuring certain words in a text for privacy or censorship purposes.
Problem Statement
Develop a program in Java that takes a sentence and a word to be censored as input, then outputs the sentence with the specified word replaced by asterisks, while preserving the original format of the sentence.
Input
This is a sample only, the sky is blue, water is transparent
Output
This is a ****** only, the sky is blue, water is transparent
Steps to replace a word with asterisks in a sentence
- START.
- Define a function replace_word that accepts a sentence and a target word.
- Use a regular expression to split the sentence into an array of words based on whitespace.
- Create a string of asterisks with the same length as the word to be replaced.
- Iterate through the array of words using a for loop, replacing any occurrence of the target word with the asterisk string.
- Combine the words back into a single string, maintaining the original spacing.
- Print the modified sentence to the console.
- STOP
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 ?
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)); } }
Output
This is a ****** only, the sky is blue, water is transparent
Code Explanation
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.