简体   繁体   English

在Java中有意义地比较两个字符串

[英]Compare two strings meaningfully in Java

I've two strings which I need to compare, but I want to compare them meaningfully such that when they are numbers their actual value should be compared. 我有两个字符串需要比较,但我想有意义地比较它们,当它们是数字时,它们的实际值应该进行比较。 So far I've tried the following solution: 到目前为止,我尝试了以下解决方案:

String str1 = "-0.6";
String str2 = "-.6";
if (NumberUtils.isNumber(str1) && NumberUtils.isNumber(str2)) {
    Number num1 = NumberUtils.createNumber(str1);
    Number num2 = NumberUtils.createNumber(str2);
    System.out.println(num1.equals(num2));
} else {
    System.out.println(str1.equals(str2));
}

This works as both are converted to double s. 这适用于两者都转换为double s。
But this won't work in this case where: 但是在这种情况下这不起作用:

String str1 = "6";
String str2 = "6.0";

Is there any easy way to do this, or will I have to write my own Comparator? 有没有简单的方法可以做到这一点,还是我必须编写自己的比较器?

Instead of using the general-purpose createNumber(String) , force them to double s using createDouble(String) : 而不是使用通用的createNumber(String) ,使用createDouble(String)强制它们double

String str1 = "-0.6";
String str2 = "-.6";
if (NumberUtils.isNumber(str1) && NumberUtils.isNumber(str2)) {
    Double d1 = NumberUtils.createDouble(str1);
    Double d2 = NumberUtils.createDouble(str2);
    System.out.println(d1.equals(d2));
} else {
    System.out.println(str1.equals(str2));
}

You can probably use BigDecimal for this: 您可以使用BigDecimal

final BigDecimal b1 = new BigDecimal(str1);
final BigDecimal b2 = new BigDecimal(str2);
return b1.compareTo(b2) == 0;

You could use Double.parseDouble(String) instead. 您可以使用Double.parseDouble(String) It throws the NumberFormatException , which can be caught to inform you that you should not compare them as numbers. 它会抛出NumberFormatException ,可以捕获它以通知您不应将它们作为数字进行比较。

try {
    Double d1 = Double.parseDouble(str1);
    Double d2 = Double.parseDouble(str2);

    //Now you have your doubles
} catch (NumberFormatException e)
{
    //Could not compare as numbers, do something else
}

As suggested on the comment one of the string could be a number and the other not or vice versa or both could be a string so instead of checking if the strings are number strings I will go using try catch block. 正如评论中所建议的那样,字符串中的一个可以是number而另一个不是,反之亦然,或者两者都可以是string所以不是检查字符串是否是数字字符串,而是使用try catch块。

Like this: 像这样:

try{
    Double d1 = Double.parseDouble(str1);
    Double d2 = Double.parseDouble(str2);
    System.out.println(d1.equals(d2));
}catch(NumberFormatException ex){

    System.out.println(num1.equals(num2));

}

This first tries to compare them as numbers but if at least one of them is not a number string it will fallback to string comparison in the catch block. 这首先尝试将它们作为数字进行比较,但如果它们中的至少一个不是数字字符串,它将回退到catch块中的字符串比较。

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

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