5 回答

TA贡献1799条经验 获得超9个赞
在您的情况下,您可以使用replaceFirst(). 这只会替换您匹配的字符串的第一次出现:
String str = "City1 is beautiful than City12";
str = str.replaceFirst("City1", "Goa");
System.out.println(str);
将输出:
Goa is beautiful than City12
除此之外,您可以使用更复杂的正则表达式来匹配您的确切情况

TA贡献1825条经验 获得超6个赞
您可以使用 replaceFirst() 或 replaceAll() 方法,但如果您想在中间替换,您可以找到您要查找的事件(此处的一个示例:Occurrences of substring in a string)
使用返回的索引生成 2 个子字符串:第一部分保持不变,在第二部分中,必须替换第一个出现的位置 (replaceFirst())
最后:连接两个子串。

TA贡献1843条经验 获得超7个赞
您可以使用以下方法replaceFirst(regex, replacement):
String str = "City1 is beautiful than City12";
System.out.println(str.replaceFirst("City1", "Goa")); // Goa is beautiful than City12

TA贡献1794条经验 获得超8个赞
如果它只是关于第一部分,你也可以使用 substring 方法。例子:
String str = "City1 is beautiful than City12";
str = "Goa" + str.substring(5);

TA贡献1779条经验 获得超6个赞
如果您确定 City1 除了空格之外不会有任何字符,您可以使用:
String str = "City1 is beautiful than than City12";
str = str.replace("City1 ", "Goa ");
System.out.println(str);
与您的相同,但在替换字符串和新字符串的末尾有额外的空间
添加回答
举报