【问题标题】:How to compare two strings如何比较两个字符串
【发布时间】:2022-06-29 21:17:57
【问题描述】:

我有两个字符串,例如“2.15.4”和“2.14.3”。比较它的最佳方法是什么?是否可以使用 Comparator 进行比较?

我已经开始用类似的模式检索每个数字

Pattern first = Pattern.compile("(\\d+).");
Pattern second = Pattern.compile(".(\\d+).");
Pattern third = Pattern.compile(".(\\d+)");

【问题讨论】:

  • 将其与心中的结果进行比较?以不同于字符串自然顺序的特定方式排序?
  • 这些模式不会做你想要的,你需要避开点。

标签: java compare


【解决方案1】:

比较两个字符串的方法有很多。

第一种方法:使用等于

   String s1="Sachin";  
   String s2="Sachin";  
   String s3=new String("Sachin");  
   String s4="Saurav";  
   System.out.println(s1.equals(s2));//true  
   System.out.println(s1.equals(s3));//true  
   System.out.println(s1.equals(s4));//false  

你可以使用 compareTo()

   String s1="Sachin";  
   String s2="Sachin";  
   String s3="Ratan";  
   System.out.println(s1.compareTo(s2));//0 if the two strings are equals
   System.out.println(s1.compareTo(s3));//1(because s1>s3) (the first letter is different S>R)
   System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2021-07-05
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多