2

Possible Duplicate:
Matching a “.” in java

I have a String 1.2.4 which i want to split and get 2 to compare it with another String that i get.

I am trying to do the following

    StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
    int oldVer = Integer.parseInt(old_ver.nextToken());
    oldVer = Integer.parseInt(old_ver.nextToken());

    StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
    int newVer = Integer.parseInt(new_ver.nextToken());
    newVer = Integer.parseInt(new_ver.nextToken());

    if (oldVer == newVer) {
        return true;
    }

IS there a better way to do it using .Split()

Community
  • 1
  • 1
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

2 Answers2

6

The problemis that in Regex "." is a single character. Hence, you need to escape it using "\\."

Similarly, you can use

string.split("\\.");

EDIT:

split() method of the String class uses Pattern and Matcher internally which is normally the API used for Regex in Java.

So there is no problem going with split.

TechSpellBound
  • 2,505
  • 6
  • 25
  • 36
1

In your code, 1.2.1 would be "compatible" with 3.2.0, and this looks like a serious problem, regardless if you use String.split or not. Also, you do not need to parse version numbers into integers as you only compare for equality.

 StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
 StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
 return (old_ver.nextToken().equals(new_ver.nextToken() && 
         old_ver.nextToken().equals(new_ver.nextToken() );

You can surely do with String.split as well:

   String [] oldV = String.split(oldVersion,"\\.");
   String [] newV = String.split(newVersion,"\\.");

   return oldV[0].equals(newV[0]) && oldV[1].equals(newV[1]);

The String.split() version seems slightly shorter but but for me it looks slightly more difficult to read because:

  • It involves additional thinking step that dot (.) is a reserved char and must be escaped.
  • "Next element and then following element" seems involving less thinking effort than "element at position 0 and then element at position 1".

It may pay to have some version comparator that first compares major, then intermediate and then minor parts of the version number the way that we could have the tests like "1.2.4 or later".

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
  • wow i didnt think of that version change :P any idea how to handle this - http://stackoverflow.com/questions/14361586/android-pushing-updates-on-play-store – Harsha M V Jan 19 '13 at 11:16