Reputation: 788
I need to change several parts of a single String where the specified parts have some Characters in common; for example:
worker => working
work => worked
note :: "=>" means "changes to"
Using codes such as below put out plenty of bugs:
String txt = "work like a real worker";
String txt2 = txt.replace("worker", "working").replace("work", "worked");
As I tested the codes above, they output "worked like a real workeding", however I need to get "worked like a real working".
Upvotes: 0
Views: 228
Reputation: 2110
If you want to replace whole words, have a look at Michael's answer. If you want to replace some words that may be contained in other words without replacing the target-words of your previous replacement again, you can try adding an intermediate step like this:
String txt = "work like a real worker in the workplace";
String txt2 = txt.replace("worker", "{$1}").replace("work", "{$2}");
String result = txt2.replace("{$1}", "working").replace("{$2}", "worked");
prints
worked like a real working in the workedplace
Upvotes: 2
Reputation: 164
Use Regex
String txt = "work like a real worker";
String txt2 = txt.replaceAll("\\worker\\b", "working").replaceAll("\\work\\b", "worked");
Upvotes: -1
Reputation: 35
The problem is, that it first replaces "worker" with "working", which is correct, but after that it replaces the "work" in "working" with "worked", which results in "workeding".
As you see the "work"-replacer replaces the second work too, which it shouldn't, because it doesn't stand alone.
To avoid that, simply put a space behind the work. With the space, it will only replace a work which stands alone without anything standing behind it (because there is a space seperating it from the next word).
It will also replace the space, so make sure to put a space behind the worked too.
It should look like this:
String txt = "work like a real worker";
String txt2 = txt.replace("worker", "working").replace("work ", "worked ");
Upvotes: 1
Reputation: 44090
If you use replaceAll
rather than replace
, you can use a regular expression. A regular expression will allow you to use \b
to denote word boundaries. Doing it this way, you will only replace whole words rather than sections of words like you are doing at the moment.
String txt2 = txt.replaceAll("\\bworker\\b", "working").replaceAll("\\bwork\\b", "worked");
Upvotes: 3