par*_*625 4 java string substring
以下是我的字符串变量:
String str = "Home(om), Home(gia)";
Run Code Online (Sandbox Code Playgroud)
我想更换子om之间存在()同tom。
我能够找到()其中om存在的索引,但以下方法不起作用:
int i1 = str.indexOf("(");
int i2 = str.indexOf(")");
str = str.replace(str.substring(i1+1,i2),"tom");
Run Code Online (Sandbox Code Playgroud)
我需要结果为Home(tom), Home(gia).
这该怎么做?
replace()如果您知道要替换的子字符串的索引,我不会使用任何方法。问题是这个语句:
str = str.replace(str.substring(someIndex, someOtherIndex), replacement);
Run Code Online (Sandbox Code Playgroud)
首先计算子字符串,然后替换原始字符串中所有出现的子字符串。 replace不知道或不关心原始索引。
最好使用substring()以下方法分解字符串:
int i1 = str.indexOf("(");
int i2 = str.indexOf(")");
str = str.substring(0, i1+1) + "tom" + str.substring(i2);
Run Code Online (Sandbox Code Playgroud)