Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

"gurp bla ha ha"

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

like image 530
Magnus Avatar asked Dec 15 '22 01:12

Magnus


1 Answers

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

string.replaceFirst("ha", "gurp");
like image 63
rgettman Avatar answered Feb 23 '23 07:02

rgettman