4

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.

2
  • 5
    Did you read about String#replaceFirst? or if you don't want to use regex [StringUtils#replaceOnce(..)][1][1]:(commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/…, java.lang.String, java.lang.String)) Commented Feb 20, 2014 at 18:50
  • It is very useful to read javadoc. Commented Feb 20, 2014 at 18:52

3 Answers 3

9

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

string.replaceFirst("ha", "gurp");
Sign up to request clarification or add additional context in comments.

2 Comments

But what if you want to replace a literal dot? The OP's example is a toy one, not reflective of real world edge cases.
@Sridhar-Sarnobat "\\."
2

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.