消除字符串中的字符

时间:2016-02-07 15:58:55

标签: java string loops char

我试图消除所有出现的' X'在字符串"清理"但我一直得到一个异常的例外。我的代码出了什么问题? 我需要使用while循环和int loc来消除发生

    public static void main (String [] args)
    {
     String cleaned = "abcXabcXabc";
     char remove= 'X';
     int loc = cleaned.indexOf(remove);

     System.out.println ("before: "+ cleaned);

     while (loc != -1)
     {
     String part1= cleaned.substring(0, loc); 
     String part2= cleaned.substring(loc+1);
     cleaned = part1+part2;
     }

     System.out.println ("after: " + cleaned);
     }

2 个答案:

答案 0 :(得分:1)

问题在于您永远不会更新loc

public static void main(String[] args)
{
    String cleaned = "abcXabcXabc";
    char remove = 'X';

    int loc;
    while ((loc = cleaned.indexOf(remove)) != 1)
    {
        String part1 = cleaned.substring(0, loc);
        String part2 = cleaned.substring(loc + 1);
        cleaned = part1 + part2;
    }

    System.out.println("after: " + cleaned);
}

while语句中使用的表达式可能会让您感到困惑,我会尝试解释它:

  • 在循环之外,声明int loc;
  • 在每个循环之前,它会获得下一个X分配的新索引。
  • 通过将分配包装到括号中,可以进一步使用已分配的内容。因此,新索引在每次迭代时都会分配给loc,然后检查为-1

当然,如果您真的愿意在实际应用程序中编写类似的内容,那么您可能希望使用String.replace(target, replacement)这样的内容:

public static void main(String[] args)
{
    String cleaned = "abcXabcXabc";
    // Notice this is now a String
    String remove = "X";

    cleaned = cleaned.replace(remove, "");

    System.out.println("after: " + cleaned);
}

答案 1 :(得分:0)

public static void main (String [] args)
{
     String cleaned = "abcXabcXabc";
     char remove= 'X';
     int loc = cleaned.indexOf(remove);
     int currentPos = 0;
     String result = "";

     System.out.println ("before: "+ cleaned);

     while (loc != -1)
     {
         result = result + cleaned.substring(currentPos,loc);
         currentPos = loc+1;
         loc = cleaned.indexOf(remove, currentPos);
     }

     System.out.println ("after: " + result);
}

这应该可以胜任。您可能希望查看StringBuilder类。