如何在我的情况下比较字符串(android)

时间:2015-10-22 12:32:37

标签: android string equals

我有两个字符串,我使用此代码获取它们

final String encrypted_id = encryption.encryptOrNull(android_id);
final String preLoad = preferences.getString("pur", "no");

确保它们相同我将它们记录下来

Log.d("encrypted_id",encrypted_id);
Log.d("preferences.getString",preferences.getString("pur", "no"));

和LogCat输出就像这样

         D/encrypted_id﹕ wxgNDxqzNWNgYWrE0fxjaU07a54XBFnAToy56MAV1Y0=
D/preferences.getString﹕ wxgNDxqzNWNgYWrE0fxjaU07a54XBFnAToy56MAV1Y0=

所以我确保它们是平等的

现在我想像这样比较它们

if(preLoad.equals(encrypted_id))
    {
        Log.d("app","is premium");

    }
    else {
        Log.d("app","is not premium");
    }

但是 LogCat向我显示

D/app﹕ is not premium

问题是什么?

PS:我试过了

1 . preLoad.equalsIgnoreCase(encrypted_id)

2 . preLoad.compareTo(encrypted_id)==0

3 个答案:

答案 0 :(得分:0)

变化:

if(preLoad.equals(encrypted_id))
    {
        Log.d("app","is premium");

    }
    else {
        Log.d("app","is not premium");
    }

if(preLoad.trim().equals(encrypted_id.trim()))
    {
        Log.d("app","is premium");

    }
    else {
        Log.d("app","is not premium");
    }

答案 1 :(得分:0)

你可以试试这个:

if(stringsCompare(preLoad.trim(),encrypted_id.trim()))
    {
        Log.d("app","is premium");

    }
    else {
        Log.d("app","is not premium");
    }

stringsCompare是我为字符串比较编写的一个过程:

    public boolean stringsCompare(String firstString, String secondString){
            if(firstString.length() != secondString.length()){
                //The length of the two strings are not equal
                return false;
            }else{
                for(int i = 0; i < firstString.length(); i++)
                {
                    if (firstString.charAt(i) != secondString.charAt(i))
                    {
                        //Let's log the difference:
                        Log.d("app","Difference at char: "+i+" its value in the first string is: "+firstString.charAt(i)+" and its value in the first string is: "+secondString.charAt(i));
                        //The strings are not equal
                        return false;
                    }
                }
                //All characters were equal
                return true;
            }
}

在这种情况下,你可以看到差异,如果有的话。

答案 2 :(得分:-1)

试试这个,

if(!preLoad.trim().equals(encrypted_id.trim()))
{
    Log.d("app","is not premium");

}
else {
    Log.d("app","is premium");
}