Java仅替换字符串中第一次出现的子字符串 [英] Java replace only first occurrence of a substring in a string
本文介绍了Java仅替换字符串中第一次出现的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这在某种程度上是此问题的重复 Ruby-仅在Java中用另一个字符串替换子字符串的第一个匹配项.
This is somehow a duplicate of this problem Ruby - replace the first occurrence of a substring with another string just in java.
问题是:
我有一个字符串:"ha bla ha ha"
现在,我想用"gurp"
替换第一个(也是第一个)"ha"
:
Now I want to replace the first (and only the first) "ha"
with "gurp"
:
"gurp bla ha ha"
string.replace("ha","gurp")
不起作用,因为它将替换所有"ha"
s.
string.replace("ha", "gurp")
doesn't work, as it replaces all "ha"
s.
推荐答案
尝试仍然有效.
string.replaceFirst("ha", "gurp");
这篇关于Java仅替换字符串中第一次出现的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文