How to Compare a String with a Char

。_饼干妹妹 提交于 2019-12-01 22:31:21

问题


Guys how do i compare a String with a char ? heres my code :

private String s;
private char c;

public K(String string, char cc){
    setS(string);
    setC(cc);
}

public void setS(String string){
    this.s = string;
}

public void setC(char cc){
    this.c = cc;
}

public boolean equals(K other){
    return s.equals(c);
}

public boolean try(){
    return s.equals(c);
}

if i call my method "try" it always returns me false even if i set both s = "s" and c = 's'.


回答1:


The first thing I would say to any of my junior devs is to not use the word "try" as a method name, because try is a reserved keyword in java.

Secondly think that there are a few things which you need to consider in your method.

If you compare things of two different types they will never be the same. A String can be null. How long the string is. The first char.

I would write the method like :

public boolean isSame() {
    if (s != null && s.length() == 1 { 
        return s.charAt(0) == c;
    }
    return false;
}



回答2:


Either use char comparison (assuming s will always be of length 1):

return c == s.charAt(0);

Or use String comparison:

return s.equals(new String(new char[]{c}));


来源:https://stackoverflow.com/questions/44615987/how-to-compare-a-string-with-a-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!