How to Replace Multiple Words in a Single String in Java

How do you replace multiple words in a string at once in Java?

Change the method namereplacer to this

public static String namereplacer(String names, String replacement) {
String[] toreplace = replacement.split("\n");
for(String str: toreplace){
String [] keyValue = str.split("\t");
if(keyValue.length != 2)
continue;
names = names.replaceAll(keyValue[0], keyValue[1]);
}
return names;
}

Java Replacing multiple different substring in a string at once (or in the most efficient way)

If the string you are operating on is very long, or you are operating on many strings, then it could be worthwhile using a java.util.regex.Matcher (this requires time up-front to compile, so it won't be efficient if your input is very small or your search pattern changes frequently).

Below is a full example, based on a list of tokens taken from a map. (Uses StringUtils from Apache Commons Lang).

Map<String,String> tokens = new HashMap<String,String>();
tokens.put("cat", "Garfield");
tokens.put("beverage", "coffee");

String template = "%cat% really needs some %beverage%.";

// Create pattern of the format "%(cat|beverage)%"
String patternString = "%(" + StringUtils.join(tokens.keySet(), "|") + ")%";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(template);

StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, tokens.get(matcher.group(1)));
}
matcher.appendTail(sb);

System.out.println(sb.toString());

Once the regular expression is compiled, scanning the input string is generally very quick (although if your regular expression is complex or involves backtracking then you would still need to benchmark in order to confirm this!)

Replacing multiple substrings from a string in Java/Android

You can create a function like below:

String replaceMultiple (String baseString, String ... replaceParts) {
for (String s : replaceParts) {
baseString = baseString.replaceAll(s, "");
}
return baseString;
}

And call it like:

String finalString = replaceMultiple("This is just a string folks", "This is", "folks");

You can pass multiple strings that are to be replaced after the first parameter.

Replace multiple strings using a single function in java 8

How about:

List<String> replaced = 
lines.map(line -> line.replace("TRACE", "MYTRACE").replace("LOGS","MYLOGS").replace("EVENT","MYEVENT"))
.collect(Collectors.toList());

replace characters, one input multiple words

You need a loop to keep getting and processing the inputs. Also, I suggest you use (?i) with the regex to make it case-insensitive.

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
String enterWord, answer = "y";
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter a word: ");
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("(?i)[aeiou]", "*");
System.out.println("After replacing vowels with * it becomes " + enterWord);
System.out.print("Do you wish to conntinue[y/n]: ");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}

A sample run:

Enter a word: hello
After replacing vowels with * it becomes h*ll*
Do you wish to conntinue[y/n]: y
Enter a word: India
After replacing vowels with * it becomes *nd**
Do you wish to conntinue[y/n]: n

For a single string spanning multiple lines, the method, String#replaceAll works for the entire string as shown below:

public class Main {
public static void main(String[] args) {
String str = "break\n" +
"robert\n" +
"yeah";
System.out.println(str.replaceAll("(?i)[aeiou]", "*"));
}
}

Output:

br**k
r*b*rt
y**h

Using this feature, you can build a string of multiple lines interactively and finally change all the vowels to *.

Demo:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
String text = "";
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.println("Keep enter some text (Press Enter without any text to stop): ");
while (true) {
text = scan.nextLine();
if (text.length() > 0) {
sb.append(text).append(System.lineSeparator());
} else {
break;
}
}

System.out.println("Your input: \n" + sb);
String str = sb.toString().replaceAll("(?i)[aeiou]", "*");
System.out.println("After converting each vowel to *, your input becomes: \n" + str);
}
}

A sample run:

Keep enter some text (Press Enter without any text to stop): 
break
robert
yeah

Your input:
break
robert
yeah

After converting each vowel to *, your input becomes:
br**k
r*b*rt
y**h

How to replace multiple words with space in a string using Java

Try:

String Sample = " he saw a cat running of that pat's mat remove 's";
String resultString = Sample.replaceAll("\\b( ?'s|he|of|to|a|and|in|that)\\b", "");
System.out.print(resultString);

saw cat running pat mat remove

DEMO

http://ideone.com/Yitobz



Related Topics



Leave a reply



Submit