Java replaces only the first occurrence of a substring in a string

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

Problem:

I have a line: "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.

+4
source share
3 answers

Try the methodreplaceFirst . It uses regex, but the literal sequence "ha"still works.

string.replaceFirst("ha", "gurp");
+7
source

replaceFirst() ( Java 1.4), , :

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

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 a string only once without a regular expression in Java?)

+2
source

Source: https://habr.com/ru/post/1527976/


All Articles