问题是: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中删除所有“ fzgh”,并将其替换为String t。

10-07 20:00
查看更多