Java replace only first occurrence of a substring

2019-02-24 09:32发布

问题:

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) "ha" with "gurp":

"gurp bla ha ha"

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

回答1:

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

string.replaceFirst("ha", "gurp");


回答2:

Try using replaceFirst() (available since Java 1.4), it does just what you need:

string = string.replaceFirst("ha", "gurp");


回答3:

You should use already tested and well documented libraries in favor of writing your own code!

StringUtils.replaceOnce("aba", "a", "")    = "ba"

(copied from How to replace string only once without regex in Java?)