Java replace only first occurrence of a substring in a string

后端 未结 3 642
南笙
南笙 2020-12-11 20:23

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:

相关标签:
3条回答
  • 2020-12-11 21:01

    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?)

    0 讨论(0)
  • 2020-12-11 21:06

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

    string = string.replaceFirst("ha", "gurp");
    
    0 讨论(0)
  • 2020-12-11 21:13

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

    string.replaceFirst("ha", "gurp");
    
    0 讨论(0)
提交回复
热议问题