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.
推荐答案
尝试 replaceFirst
方法.它使用正则表达式,但文字序列 "ha"
仍然有效.
Try the replaceFirst
method. It uses a regular expression, but the literal sequence "ha"
still works.
string.replaceFirst("ha", "gurp");
这篇关于Java只替换字符串中子字符串的第一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文