M
M
Maxim2021-06-27 11:40:37
Java
Maxim, 2021-06-27 11:40:37

How to replace a word?

In general, there is a String str variable that can contain a word, for example "LOG", only one word can be contained in this variable, I need this word to change to the specified one, let's say if str is equal to the word "LOG", then the new variable newstr was assigned the desired to me the value is acceptable "OAK" , how to fix one word I know String strnew = str.replace("LOG", "OAK"); but what to do if str becomes WOOD rather than LOG and it is replaced by WOOD.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-06-27
@MaximPython

Map<String, String> replacements = new Map.of(
  "LOG", "ДУБ",
  "WOOD", "ДЕРЕВО"
);

String strnew = replacements.entrySet()
    .stream()
    .reduce(str, (acc, e) -> acc.replace(e.getKey(), e.getValue()));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question