Magnus Magnus - 1 year ago 100
Java Question

Java replace only first occurrence of a substring in a string

This is somehow a duplicate of this problem Ruby - replace the first occurrence of a substring with another string just in java.

Problem is:

I have a string:

"ha bla ha ha"

Now I want to replace the first (and only the first)

"gurp bla ha ha"

string.replace("ha", "gurp")
doesn't work, as it replaces all

Answer Source

Try the replaceFirst method. It uses a regular expression, but the literal sequence "ha" still works.

string.replaceFirst("ha", "gurp");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download