Michael Michael - 1 year ago 57
Java Question

How to replace a specific string in Java?

I usually don't ask for help but here I really need it.

I have the following code example:

String text = "aa aab aa aab";
text = text.replace("aa", "--");

Console output: -- --b -- --b

I have a question, how do I only replace aa parts of the string not aab included.

So the console output is:

-- aab -- aab

I have another example:

String text = "111111111 1";
text = text.replace("1", "-");

Console output: --------- -

I only want to replace a single character, not all the same ones who are placed together.

So the console output is:

111111111 -

Are there any Java shortcuts for situations like these? I can't figure it out, how to only replace specific part of the string.
Any help would be appreciated :)

Answer Source

You could use a regular expression with String.replaceAll(String, String). By using word boundaries (\b), something like

String[] texts = { "aa aab aa aab", "111111111 1" };
String[] toReplace = { "aa", "1" };
String[] toReplaceWith = { "--", "-" };
for (int i = 0; i < texts.length; i++) {
    String text = texts[i];
    text = text.replaceAll("\\b" + toReplace[i] + "\\b", toReplaceWith[i]);

Outputs (as requested)

-- aab -- aab
111111111 -
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download