Java 如何比较字符串和字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44615987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Compare a String with a Char
提问by user8120322
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'
.
如果我调用我的方法try
,它总是返回 false,即使我设置了s = "s"
和c = 's'
。
采纳答案by MartinByers
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.
我要对任何初级开发人员说的第一件事是不要将“try”一词用作方法名称,因为 try 是 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;
}
回答by ernest_k
Either use char comparison (assuming s will always be of length 1):
要么使用字符比较(假设 s 的长度总是为 1):
return c == s.charAt(0);
Or use String comparison:
或者使用字符串比较:
return s.equals(new String(new char[]{c}));