V
V
Vladyslav GmGameFilm2016-08-02 13:58:38
Java
Vladyslav GmGameFilm, 2016-08-02 13:58:38

How to implement a method so that it replaces one word with another?

They gave me a task, the essence of which is to replace all occurrences of the word "byaka" with *censored*.
During the execution of the task, I encountered the following problem: The String class is immutable (immutable). Because of this, when a String variable is assigned the value obtained from the next() method in the Scanner class (java.util, the System.in parameter was passed to the constructor) and when the replaceAll(String a, String b) method is called on the variable ( String class, java.lang) results in nothing. If I give "you are a badass" at the entrance, "you" will come out.
I tried to use the StringBuffer class, but the methods there are replaced only by indexes, and I need it to find this word and replace it, regardless of which index it is located at.
Question: How should the method be implemented so that it produces the replaced "bug" as a result?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evhen, 2016-08-02
@GmGameFilm

The String class replaceAll method returns a new String object with the changes made.
String textAfterCensure = textBeforeCensure.replaceAll("bad", "*");

A
Anton, 2016-08-02
@MoonMaster

If my memory serves me, then there is a wonderful method Replace All , which receives a pattern and a substitute (what needs to be replaced) as input. After that it returns a String.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question