0

I want to remove 'a' and 'b' from the string but the whole string will print in the end, I do not understand what is happening in this code because the code will run properly when I use other methods.

public class Test
    {
        public static void main(String[] args)
        {
            String st = "abracadabra";
            String newst = "";
            int len = st.length();
            for(int i=0; i<len; i++)
            {
                char ch = st.charAt(i);
                if(ch!='a' || ch!='b')
                {
                   newst= newst+ ch;
                }
            }
            System.out.println(newst);
        }

    }
  • 1
    Does this answer your question? [Why non-equality check of one variable against many values always returns true?](https://stackoverflow.com/questions/26337003/why-non-equality-check-of-one-variable-against-many-values-always-returns-true) – Savior Apr 09 '20 at 03:41
  • 1
    You want `&&` you used `||`. Consider the letter 'a', is 'a' not 'a' - no; but is 'a' not 'b' - yes! – Elliott Frisch Apr 09 '20 at 03:44

3 Answers3

0

you can do this instead of looping through string to replace a and b from your string:

    String st = "abracadabra";       
    st = st.replaceAll("[ab]", "");        
    System.out.println(st);

Output is :

rcdr
Reeta Wani
  • 197
  • 4
  • 13
0
public class Test

{
    public static void main(String[] args)
    {
        String st = "abracadabra";


        String newst = "";
        int len = st.length();
        for(int i=0; i<len; i++)
        {
            char ch = st.charAt(i);
            if(ch!='a' && ch!='b')
            {
                System.out.println(ch);
            }
        }
        System.out.println(newst);
    }

}
-1
if(ch!='a' || ch!='b')

... should be

if(ch!='a' && ch!='b')
rtx13
  • 2,580
  • 1
  • 6
  • 22