你好像下面的字符串
String str =" vishwa sgsu shishs sjishs vishwa sjsjos vishwa&#34 ;;
我必须替换下面的每个事件
所以我的结果字符串将如下所示
" xyz sgsu shishs sjishs yzk sjsjos jey"
我尝试使用replaceFirst(),replace()方法,但没有工作。
我该怎么做??
答案 0 :(得分:3)
如果您需要更强大的功能,请使用此功能 -
String original = "vishwa sgsu shishs sjishs vishwa sjsjos vishwa";
String s = "vishwa";
String [] replacements = { "xyz", "yzk", "jey" };
for (int i = 0; i < replacements.length; i++) {
if (original.contains(s)) {
original = original.replaceFirst(s, replacements[i]);
} else {
break;
}
}
System.out.println(original);
如果你需要替换更多字符串,循环就可以完成工作。
答案 1 :(得分:2)
请使用以下代码并检查您的输出。
String str = "vishwa sgsu shishs sjishs vishwa sjsjos vishwa";
String strNewString = str.replace("vishwa","xyz");
strNewString = strNewString.replace("vishwa","yzk");
strNewString = strNewString.replace("vishwa","jey");
现在使用strNewString作为将来使用。
答案 2 :(得分:0)
试试
String someString = "vishwa sgsu shishs sjishs vishwa sjsjos vishwa";
someString = someString.replaceFirst("vishwa","xyz");
someString = someString.replaceFirst("vishwa","yzk");
someString = someString.replaceFirst("vishwa","jey");
答案 3 :(得分:-1)
由于replaceFirst创建了一个新字符串,你可以通过
来完成 String result = str.replaceFirst("vishwa", "xyz")
.replaceFirst("vishwa", "yzk")
.replaceFirst("vishwa", "jey")