在Stringbuilder中删除字符后索引混淆 - Java

时间:2018-06-11 18:41:50

标签: java string stringbuilder

public static String RemoveChar(String s,char a,char b)
    {
        StringBuilder sb = new StringBuilder(s);
        for(int i=0;i < sb.length();i++)
        {
            if(sb.charAt(i)==a || sb.charAt(i)==b)
            {   System.out.println("Characters removed are : "+a+" "+b);
                System.out.println("Removed character at "+i+" : "+s.charAt(i));
                sb.deleteCharAt(i);

            }
        }
        return sb.toString();
    }



    **Input** :  RemoveChar("beabeefeab",'a','b');
    **Output** : Characters removed are : a b
    Removed character at 0 : b
    Characters removed are : a b //It checks if the character at the index is a or b
    Removed character at 1 : e //after it passes the if condition it removes e.Why does this happen? What alternative can i do for this?
    Characters removed are : a b
    Removed character 6 : f
    ebeefeb

我是stringbuilder和java的新手,请原谅我这是一个愚蠢的问题。建议另一个选择并告诉我这里出了什么问题。对于这个初学者来说真的很有用:)

2 个答案:

答案 0 :(得分:0)

当您致电deleteCharAt时,您会删除索引i处的字符,该字符会将其余字符向左移动一个位置。因此,在这种情况下,您不应该将索引计数器i增加一个。

试试这个

for(int i=0; i < sb.length() ; )
    {
        if(sb.charAt(i)==a || sb.charAt(i)==b)
        {   System.out.println("Characters removed are : "+a+" "+b);
            System.out.println("Removed character at "+i+" : "+sb.charAt(i));
            sb.deleteCharAt(i);
        } else {
           i++;
        }
    }

答案 1 :(得分:0)

删除索引i处的字符后,使用位于i + 1位置的字符现在位于i位置,且字符为曾经在i + 2的人现在在i + 1。然后,您递增i,这样您就可以查看以前在索引i + 2中的字符,并跳过索引i+1处的字符。

简单的解决方案包括向后迭代,或在i--内执行if