Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to use replace multiple words in a string [duplicate]

Tags:

java

replace

At the moment I'm doing

Example:

line.replaceAll(",","").replaceAll("cat","dog").replaceAll("football","rugby"); 

I think that it ugly. Not sure a better way to do this? Maybe loop through a hashmap?

EDIT:

By efficiency I mean better code style and flexibility

like image 954
Decrypter Avatar asked Oct 05 '11 08:10

Decrypter


People also ask

How do you replace multiple values in a string?

var str = "I have a cat, a dog, and a goat."; str = str. replace(/goat/i, "cat"); // now str = "I have a cat, a dog, and a cat." str = str. replace(/dog/i, "goat"); // now str = "I have a cat, a goat, and a cat." str = str.

How do you replace multiple substrings in a string in Python?

Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() . Specify a dictionary whose key is the old character and whose value is the new string in the str.

How do you replace multiple words with one word in Excel?

If you press Ctrl+H, it will bring up the Find/Replace dialog box. You can enter what you're looking for, enter what you want to replace it with and press a button. For changing the text color, select the range necessary, and go to Format|Conditional Formatting.


1 Answers

This functionality is already implemented in Commons Lang's StringUtils class.

StringUtils.replaceEach(String text, String[] searchList, String[] replacementList) 
like image 189
Mukesh Koshy M Avatar answered Sep 17 '22 13:09

Mukesh Koshy M