java Equals()对于两个相等的字符串不返回true
我没有找到两个字符串不相等的原因。这是我的密码:
public static void main(String[] args) {
JTextArea jt=new JTextArea();
jt.append("why \n me?"); //i set a test value to the JTextArea
Document doc = jt.getDocument();
Element root = doc.getDefaultRootElement();
Element element = root.getElement(0);
int start = element.getStartOffset();
int end = element.getEndOffset();
//the code above is what i specifically need for my app, to bring a
//specific line from a JTextArea
String s;
try {
s=doc.getText(start, end - start);
System.out.print("s = "+s);
if(s.equals("why")) //i expect equals() here to return true
System.out.print("s equals "+s);
else
System.out.print("s is not equal to "+s);
} catch (BadLocationException ex) {
ex.getStackTrace();
}
}
运行程序后得到的结果是:
s = why
s is not equal to why
# 1 楼答案
最可能的解释是
s
字符串实际上是"why "
。注意空格字符事实上,如果您查看附加到JTextArea的字符串,在“为什么”之后和换行符之前都有空格
一般来说,当出于调试目的显示字符串时,最好在其周围加引号,以便注意到任何前导或尾随空格。例如:
另一种可能的解释(尽管在这种情况下不太可能)是homoglyphs;i、 e.两个不同的Unicode代码点,在一个典型字体中看起来彼此类似
# 2 楼答案
如果要比较两个字符串对象的内容,可以使用
s.compareTo("why")==0
# 3 楼答案
如果您使用eye catcher打印出来:
System.out.print("s = >>" + s +"<<");
您可以看到,在末尾,您包含了空格和换行符:
而且
why \n
不等于why
使用s = doc.getText(start, end - start).trim();
它应该可以工作# 4 楼答案
结果必须有一个空格,因为新行前面有一个空格
您
end
正在\n
之前包含空格。你需要写作或者,您可以在比较时对其进行修剪,因为这只是空间注意,如果你有其他字母而不是空格,修剪就不起作用了