如何在不使用Java中的Regex的情况下处理不区分大小写的字符串替换

时间:2012-02-05 04:08:41

标签: java string

这是来自CodingBat网站的问题。我先解决问题并在此之后讨论我的努力:

  

给定两个字符串base和remove,返回基本字符串的一个版本,其中删除了删除字符串的所有实例(不区分大小写)。您可以假设删除字符串的长度为1或更长。仅删除不重叠的实例,因此使用“xxx”删除“xx”会留下“x”。

withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"

这是我到目前为止写的:

public String withoutString(String base, String remove) {

   int len_b=base.length();
   int len_r = remove.length();
   String result="";

   if(len_b<1 || len_r<1)
   return "";

   for (int i =0;i<=len_b-len_r;i++)
   {
      if(base.substring(i,i+len_r).equals(remove))
      {
        i=i+len_r-1;
      }

      else
      { 
        result=result+base.substring(i,i+1);
      }  
   } 

   if(!(base.substring(len_b-len_r+1, len_b).equals(remove)))
   result=result+base.substring(len_b-len_r+1, len_b);

return result;
}

这会传递所有测试用例,除了删除字符串不区分大小写的情况。

例如:withoutString("This is a FISH", "IS") → "Th a FH"

我的代码给了我“这是一个FH”,因为我在代码中没有处理区分大小写。我知道使用Regex可以在一行中完成。我更感兴趣的是知道在我现在的代码中是否有办法处理这些类型的测试用例。 另外,如果我的代码更高效/更优雅,请告诉我。

5 个答案:

答案 0 :(得分:6)

字符串有equalsIgnoreCase(String s)方法。

答案 1 :(得分:1)

您可以使用base.substring(i,i+len_r).equals(remove)方法将此语句base.substring(i,i+len_r).equalsIgnoreCase(remove)更改为equalsIgnoreCase

希望对你有所帮助。

答案 2 :(得分:0)

public String withoutString(String base, String remove) 
{
    String str=base;
    String str1=remove;
    String str3=str;

    int k=str1.length();

    for(int i=0;i<(str.length()-k+1);i++)
    {
        if(str1.equalsIgnoreCase(str.substring(i, i+k)))
        {
            String str4=str.substring(i, i+k);
            str3=str3.replaceFirst(str4,"" );

        }
    }
    return str3;
}

答案 3 :(得分:0)

我做到了没有任何循环:)我想这不是最好的答案,但它可以工作

public String withoutString(String base, String remove) {
    String lastString = base.replace(remove, "");
    remove = remove.toLowerCase();
    String veryLastString = lastString.replace(remove, "");
    remove = remove.toUpperCase();
    String veryVeryLastString = veryLastString.replace(remove, "");
    return veryVeryLastString;
}

答案 4 :(得分:0)

public String withoutString(String base, String remove) {
      String b=base.toLowerCase();
      String r=remove.toLowerCase();
      if(b.length()<r.length()) return base;
      if(b.contains(r)) b=b.replaceAll(r,"");
      String temp="";
      int j=0;
      for(int i=0;i<base.length();i++)
        if(j<b.length()){
          if(base.substring(i,i+1).equalsIgnoreCase(b.substring(j,j+1))){
            temp+=base.substring(i,i+1);
            j++;
          }
        }  
      return temp;
    }