简体   繁体   中英

String comparison returns wrong result

I trying to compare 2 strings in Java to determine if they are the same:

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",""); 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.

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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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