简体   繁体   中英

How do I compare two numeric string in Java?

I would like to compare two numeric string such as "1.0.1" and "2.1.1". May I know that is there any string utility method in Java to compare or need to implement like remove .(dot), parse to integer and compare manually? Thank you.

remove .(dot)

myString.replaceAll("\\.","")

parse to integer

int myInt = Integer.parseInt(myString);

compare manually

if(myInt < myInt2) { // ....

You can use String.replaceAll(String regex, String replacement) to replace all the dots with an empty string.

String str1 = "1.0.1";
str1 = str1.replaceAll(".","");
int num1 = Integer.parseInt(str1);
// similarly for num2
String str2 = "2.1.2";
str2 = str2.replaceAll(".","");
int num2 = Integer.parseInt(str2);
if (num1 == num2)
// do Something
else
// do Something else.

You can use mystr.replace('.', '') and compare using mystr.equals(mystr2) . Or to compare the strings as number you could parse to Integer, like so:

myInt = Integer.parseInt(mystr);
if(myInt == myInt2) {
   // do something
}

Split the strings on the dot ( string.split("\\\\.") — you have to escape the . since split takes a regex, and you have to escape the escape because you're typing it as a Java string literal), and then parse and compare each component from the two strings. As you do so, if the components are unequal, there's your answer; otherwise, go on to the next one. If there isn't a next one, the two strings are equal.

For instance, given "1.2.3" and "1.4.5", the splits would be ["1", "2", "3"] and ["1", "4", "5"]. So you'd first parse and compare the strings at index 0; they're both 1, so you go to the next index. Then you parse and compare the strings at index 1; 2 < 3, so "1.2.3" < "1.4.5".

Depending on your use case, you may also need to cover use cases like if they have different number of components (for instance, "1.2.3" vs "1.2").

Do not just remove the dot, as other answers have said, unless you want 2.3.4 to be lower than 1.23.4, since 234 < 1234.

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