Java replace only first occurrence of a substring in a string

后端 未结 3 652
南笙
南笙 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:06

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

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

提交回复
热议问题