问题是:mutation()
传递两个字符串并返回一个字符串。 fzgh
第一个字符串中出现的所有内容都将替换为第二个字符串。
mutation("Hello. I want an fzgh. Give me an fzgh now.", "IPhone 6")-> "Hello. I want an IPhone 6. Give me an IPhone 6 now."
这是我的尝试:
public static String mutation(String s, String t){
int f=s.indexOf("fzgh");
String w="";
if(f !=-1){
w=w+s.substring(0,f)+t;
}
return w;
}
我知道有.replace()
,但我们不被允许使用它。我们必须使用 indexOf()
最佳答案
你可以这样定义突变
public static String mutation(String s,String t){
int f=s.indexOf("fzgh");
int l =4;//length of "fzgh"
String w = s;
while(f!=-1){
w=w.substring(0,f)+t+w.substring(f+l,w.length());
f=w.indexOf("fzgh");
}
return w;
}
这将从 String s 中删除所有“fzgh”并将其替换为 String t。
关于java - 不使用replace()用字符串替换子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33490399/