i want to remove 'a' and 'b' from the string but whole string will print in the end, why?

huangapple 未分类评论46阅读模式
英文:

i want to remove 'a' and 'b' from the string but whole string will print in the end, why?

问题

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);
    }
}
英文:

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 = &quot;abracadabra&quot;;
    		String newst = &quot;&quot;;
    		int len = st.length();
    		for(int i=0; i&lt;len; i++)
    		{
    			char ch = st.charAt(i);
    			if(ch!=&#39;a&#39; || ch!=&#39;b&#39;)
    			{
    			   newst= newst+ ch;
    			}
    		}
    		System.out.println(newst);
    	}
    	
    }

答案1

得分: 0

你可以使用以下代码来替代循环遍历字符串并替换其中的a和b:

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

输出结果为:

rcdr
英文:

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

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

Output is :

rcdr

答案2

得分: 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);
    }
}
英文:
public class Test

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


        String newst = &quot;&quot;;
        int len = st.length();
        for(int i=0; i&lt;len; i++)
        {
            char ch = st.charAt(i);
            if(ch!=&#39;a&#39; &amp;&amp; ch!=&#39;b&#39;)
            {
                System.out.println(ch);
            }
        }
        System.out.println(newst);
    }

}

答案3

得分: -1

if(ch!='a' && ch!='b')
英文:
if(ch!=&#39;a&#39; || ch!=&#39;b&#39;)

... should be

if(ch!=&#39;a&#39; &amp;&amp; ch!=&#39;b&#39;)

huangapple
  • 本文由 发表于 2020年4月9日 11:40:36
  • 转载请务必保留本文链接:https://java.coder-hub.com/61113570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定