创建一个名为filter的方法,它有两个字符串参数并返回一个字符串

时间:2017-11-13 04:52:40

标签: java string

该方法将从第一个sting过滤掉所有出现的第二个字符串。过滤器区分大小写。如果第二个参数是CAT,请不要过滤掉cat。

public static void main(String[] args){        // should filter out the   
  System.out.println("method: filter");       // second string
  System.out.println(filter( "CS221 is terrible", "terrible"));
  System.out.println(filter( "my cat is a nice cat", "cat"));
  System.out.println(filter( "ababababa","ab"));
  System.out.println(filter( "not here", "a"));
  System.out.println(filter( "abababab","ab"));
  System.out.println(filter( "CATcatCAT","CAT"));
  System.out.println(filter( "dark","k"));
  System.out.println(filter("ususerer", "user"));
}
public static String filter ( String str, String filter){
  String temp = "";
  int i = 0;

  while(i < str.length() && str.indexOf(filter,i) != -1){                                            
     if(str.indexOf(filter,i)!=-1){
         temp+=str.substring(i, str.indexOf(filter,i));
     }else{
         temp+=str.substring(i,str.length());
     }
     i = str.indexOf(filter, i)+ filter.length();
     i++;
  }
  return temp;

}
  

输出代码

 CS221 is 
 my is a nice 
 b

 b
 at
 dar
 us
  

预期输出

 CS221 is 
 my is a nice
 a
 not here
 nothing prints at all on this line its just blank
 cat
 dar
 user

3 个答案:

答案 0 :(得分:0)

这完全没问题。

     public static void main(String[] args){        // should filter out the   
     System.out.println("method: filter");       // second string
     System.out.println(filter( "CS221 is terrible", "terrible"));
     System.out.println(filter( "my cat is a nice cat", "cat"));
     System.out.println(filter( "ababababa","ab"));
     System.out.println(filter( "not here", "a"));
     System.out.println(filter( "abababab","ab"));
     System.out.println(filter( "CATcatCAT","CAT"));
     System.out.println(filter( "dark","k"));
     System.out.println(filter("ususerer", "user"));
     }
  public static String filter ( String str, String filter)
  {
     String temp = "";
     int i = 0;
     if(str.indexOf(filter,i) == -1)
     {
        return temp;
     }
   else
   {
       return str.replace(filter,"");
    }

    }

答案 1 :(得分:0)

我不知道你为什么重新发明轮子......

public static String filter (String str, String filter)
    return str.replaceAll(" ?" + filter, "");
}

您需要使用正则表达式来获取可选的前导空格,该空格变为:

"my cat is a nice cat" // input
"my is a nice"         // output correct as per your question

如果您使用普通替换,即str.replace(filter, ""),则会产生此效果:

"my cat is a nice cat" // input
"my  is a nice "       // incorrect: notice the double spaces

答案 2 :(得分:0)

为什么不能使用replaceAll

public static String filter(String str, String filter) {
    return str.replaceAll(filter, "").replaceAll("\\s{2,}", " ");
}