![]() |
VOOZH | about |
For the given sentence as input, censor a specific word with asterisks ' * '.
Example :
Input : word = "computer"
text = "GeeksforGeeks is a computer science portal for geeks. People who love computer and computer codes can contribute their valuables/ideas on computer codes/structures on here."
Output : GeeksforGeeks is a ******** science portal for geeks. People who love ******** and ******** codes can contribute their valuables/ideas on ******** codes/structures on here.
The idea is to first split given sentence into different words. Then traverse the word list. For every word in the word list, check if it matches with given word. If yes, then replace the word with stars in the list. Finally merge the words of list and print.
Implementation:
GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science.
Complexity Analysis:
Approach : Using replace() in python3.
Replace() method searches for the string passed as the first argument in the given string and then replaces that with the second argument.
Implementation:
GeeksforGeeks is a ******** science portal for geeks.\I am pursuing my major in ******** science.
You can use the re module in Python to search for the specific word in the sentence and replace it with the asterisks.
Using
The censor function takes two parameters, text and word.
It searches for all occurrences of word in text using a regular expression with the global g flag, and replaces each occurrence with asterisks of the same length using the replace function.
GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science.
This approach has a time complexity of O(N), where N is the length of the text. The auxiliary space required is O(1).
In the regular expression, we pass the word variable as the pattern to search for. The g flag means that it will find all occurrences of the pattern, not just the first one.
In the replace function, we pass a callback function that returns an asterisk (*) repeated for the length of the matched string.
This ensures that the asterisks have the same length as the word that was replaced.
GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science.
Time complexity: O(n), where n is the length of the input text string.
Space complexity: O(1).