java - 对于两个相等的字符串,Equals() 不返回 true

标签 java string function character-encoding equals

我未能找到两个字符串不相等的原因。这是我的代码:

  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

最佳答案

您的结果必须有一个空格,因为新行之前有一个空格

 s=doc.getText(start, end - start);

end 包含\n 之前的空格。你需要写

 s=doc.getText(start, (end -1) - start);

或者您可以在比较时修剪它,因为它只是空格。 请注意,如果您有除空格之外的其他字母,修剪将不起作用。

关于java - 对于两个相等的字符串,Equals() 不返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43869535/

相关文章:

java - Freebase Java API 全文检索

python - 我的 python 计算器返回一个字符串,而不是正确的数学运算序列

c - 在将 void* 转换回 String 时遇到一些问题

php - 如何让 in_array() 不区分大小写?

javascript - 无法使用socketIO获取对象内部函数的值

function - 不能在函数中调用管道属性。电源外壳

java - 辅导日志,混淆 JButton 的代码

java - 如何处理实体中的任何字段更改(Spring Boot)

java - 计算复杂度时是: does a[0] + a[1] result in two array accesses,还是只有一个?

javascript - 获取子属性