简体   繁体   English

字符串比较返回错误的结果

[英]String comparison returns wrong result

I trying to compare 2 strings in Java to determine if they are the same: 我试图比较Java中的2个字符串,以确定它们是否相同:

System.out.println("app version: "+ appversion + " latest version: "+ latestversion); 

if(!appversion.equals(latestversion))
{            
    System.out.println("not the same"); 
}

However this is giving me unexpected results given the outputs: 然而,鉴于产出,这给了我意想不到的结果:

app version: v1.1.2 latest version: v1.1.2
not the same

I have used .replaceAll("\\\\s",""); 我使用过.replaceAll("\\\\s",""); to remove any whitespaces from the strings with no success. 从字符串中删除任何空格都没有成功。

There is probably a very obvious answer to this but can anyone tell me what i'm doing wrong? 可能有一个非常明显的答案,但任何人都可以告诉我我做错了什么?

您是否尝试在两个字符串上使用.trim()?

Instead of .replaceAll() method, use trim() method to remove white space while comparing String variables. 而不是.replaceAll()方法,使用trim()方法在比较String变量时删除空格。

change your code as follows as, 更改您的代码如下,

if(!appversion.trim().equals(latestversion.trim()))
{            
    System.out.println("not the same"); 
}

buddy try this 哥们试试这个

System.out.println("app version: "+ appversion.trim() + " latest version:"+latestversion.trim()); 

if(!appversion.trim().equals(latestversion.trim()))
{            
    System.out.println("not the same"); 
} 

Code is running fine:- 代码运行正常: -

 String appversion=" v1.1.2";
      String latestversion=" v1.1.2";
      if(!appversion.equals(latestversion))
      {            
      System.out.println("not the same"); 
      }

Or you can use:- 或者您可以使用: -

if(!appversion.trim().equals(latestversion.trim()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM