【问题标题】:Comparing strings that use the substring method [duplicate]比较使用子字符串方法的字符串[重复]
【发布时间】:2014-09-06 14:49:19
【问题描述】:

我希望有人能给我解释为什么下面的代码不起作用:

            //Why doesnt this work
            String l = myString.substring(cut,  lengthLastBtn-1);
            String c = myString.substring(cut,  lengthLastBtn-1);

            if(l==c){
                Log.i(TAG, "Correct");
            }
            //End

            //This work!
            String l = "hi";
            String c = "hi";

            if(l==c){
                Log.i(TAG, "Correct");
            }
            // End

            // Or if i want the Vars as in the first code i have to use the if statement like this
            if(l.contains(c)){
                Log.i(TAG, "Correct");
            }
            //End

那么,当我使用了 substring 方法后,为什么不能比较一个字符串。我什至在日志中看到它们是相同的,或者至少具有相同的文本。

【问题讨论】:

  • == 按对象标识而不是内容比较字符串。
  • 你应该改用equals() 方法。
  • strings that use the substring method 是什么?!
  • 感谢您的快速回复,equals 成功了。该链接非常有用。

标签: android substring


【解决方案1】:

当您将“==”运算符与 String`s 一起使用时,它意味着对象之间的比较,而不是对象所持有的值。

为了比较Strings 的值,你应该使用内置方法equals。如果String 对象表示相同的字符序列,则结果为真。

if(string1.equals(string2)) {
     //Match 
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多