Compare Version Numbers Without Using Split Function

Compare version numbers without using split function

Can you use the Version class?

https://learn.microsoft.com/en-us/dotnet/api/system.version

It has an IComparable interface. Be aware this won't work with a 5-part version string like you've shown (is that really your version string?). Assuming your inputs are strings, here's a working sample with the normal .NET 4-part version string:

static class Program
{
static void Main()
{
string v1 = "1.23.56.1487";
string v2 = "1.24.55.487";

var version1 = new Version(v1);
var version2 = new Version(v2);

var result = version1.CompareTo(version2);
if (result > 0)
Console.WriteLine("version1 is greater");
else if (result < 0)
Console.WriteLine("version2 is greater");
else
Console.WriteLine("versions are equal");
return;

}
}

C# how can you compare versions?

Use the semantic version library for .Net

To install the package:

 Install-Package semver

You can parse /compare versions.

Example 1: Compare

     var v1 = new SemVersion(1, 0, 0, "rc1");
Console.WriteLine(v1);
var v2 = new SemVersion(1, 0, 0, "rc2");
Console.WriteLine(v2);
var r = SemVersion.Compare(v1,v2);
//If v1 < v2 return -1
//if v1 > v2 return +1
//if v1 = v2 return 0
Console.WriteLine(r); // -1

Example2: Parse

     var version = SemVersion.Parse("1.2.45-alpha-beta+nightly.23.43-bla");
Console.WriteLine(version);
Console.WriteLine( version.Major); //1
Console.WriteLine( version.Minor); //2
Console.WriteLine( version.Patch); //45
Console.WriteLine(version.Prerelease); //alpha-beta
Console.WriteLine(version.Build); //nightly.23.43

Update:

Life demo in fiddle

Compare two version numbers (true if different minor version)

awk may help for this case. Here's a simple script to do that,

#!/bin/bash

old_version="$1"
new_version="$2"

awk -v u=${old_version} -v v=${new_version} '
BEGIN{
split(u,a,".");
split(v,b,".");
printf "old:%s new:%s => ",u,v;
for(i=1;i<=2;i++) if(b[i]!=a[i]){print "true";exit}
print "false"
}'

The script would only compare major and minor version number, return false if they're matched, else return true.

How can I compare software version number using JavaScript? (only numbers)

The basic idea to make this comparison would be to use Array.split to get arrays of parts from the input strings and then compare pairs of parts from the two arrays; if the parts are not equal we know which version is smaller.

There are a few of important details to keep in mind:

  1. How should the parts in each pair be compared? The question wants to compare numerically, but what if we have version strings that are not made up of just digits (e.g. "1.0a")?
  2. What should happen if one version string has more parts than the other? Most likely "1.0" should be considered less than "1.0.1", but what about "1.0.0"?

Here's the code for an implementation that you can use directly (gist with documentation):

function versionCompare(v1, v2, options) {
var lexicographical = options && options.lexicographical,
zeroExtend = options && options.zeroExtend,
v1parts = v1.split('.'),
v2parts = v2.split('.');

function isValidPart(x) {
return (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/).test(x);
}

if (!v1parts.every(isValidPart) || !v2parts.every(isValidPart)) {
return NaN;
}

if (zeroExtend) {
while (v1parts.length < v2parts.length) v1parts.push("0");
while (v2parts.length < v1parts.length) v2parts.push("0");
}

if (!lexicographical) {
v1parts = v1parts.map(Number);
v2parts = v2parts.map(Number);
}

for (var i = 0; i < v1parts.length; ++i) {
if (v2parts.length == i) {
return 1;
}

if (v1parts[i] == v2parts[i]) {
continue;
}
else if (v1parts[i] > v2parts[i]) {
return 1;
}
else {
return -1;
}
}

if (v1parts.length != v2parts.length) {
return -1;
}

return 0;
}

This version compares parts naturally, does not accept character suffixes and considers "1.7" to be smaller than "1.7.0". The comparison mode can be changed to lexicographical and shorter version strings can be automatically zero-padded using the optional third argument.

There is a JSFiddle that runs "unit tests" here; it is a slightly expanded version of ripper234's work (thank you).

Important note: This code uses Array.map and Array.every, which means that it will not run in IE versions earlier than 9. If you need to support those you will have to provide polyfills for the missing methods.

How do you compare two version Strings in Java?

Tokenize the strings with the dot as delimiter and then compare the integer translation side by side, beginning from the left.

How do I compare version numbers in Python?

Use packaging.version.parse.

>>> # pip install packaging
>>> from packaging import version
>>> version.parse("2.3.1") < version.parse("10.1.2")
True
>>> version.parse("1.3.a4") < version.parse("10.1.2")
True
>>> isinstance(version.parse("1.3.a4"), version.Version)
True
>>> isinstance(version.parse("1.3.xy123"), version.LegacyVersion)
True
>>> version.Version("1.3.xy123")
Traceback (most recent call last):
...
packaging.version.InvalidVersion: Invalid version: '1.3.xy123'

packaging.version.parse is a third-party utility but is used by setuptools (so you probably already have it installed) and is conformant to the current PEP 440; it will return a packaging.version.Version if the version is compliant and a packaging.version.LegacyVersion if not. The latter will always sort before valid versions.

Note: packaging has recently been vendored into setuptools.


An ancient and now deprecated method you might encounter is distutils.version, it's undocumented and conforms only to the superseded PEP 386;

>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("1.3.a4")
Traceback (most recent call last):
...
ValueError: invalid version number '1.3.a4'

As you can see it sees valid PEP 440 versions as “not strict” and therefore doesn’t match modern Python’s notion of what a valid version is.

As distutils.version is undocumented, here are the relevant docstrings.

Comparing version numbers

I don't know of anything built in that will do it, but I have heard that the Sparkle framework has a version comparator.

Browsing quickly through the source reveals that the SUStandardVersionComparator object seems to be in charge of it. It conforms to the <SUVersionComparison> protocol,which means you could probably just use it like this:

NSString *versionA = @"1.2.1";
NSString *versionB = @"1.2.0";
id <SUVersionComparison> comparator = [SUStandardVersionComparator defaultComparator];
NSInteger result = [comparator compareVersion:versionA toVersion:versionB];
if (result == NSOrderedSame) {
//versionA == versionB
} else if (result == NSOrderedAscending) {
//versionA < versionB
} else {
//versionA > versionB
}

(note: code untested and typed in a browser. Caveat Implementor)

Efficient way to compare version strings in Java

Requires commons-lang3-3.8.1.jar for string operations.

/**
* Compares two version strings.
*
* Use this instead of String.compareTo() for a non-lexicographical
* comparison that works for version strings. e.g. "1.10".compareTo("1.6").
*
* @param v1 a string of alpha numerals separated by decimal points.
* @param v2 a string of alpha numerals separated by decimal points.
* @return The result is 1 if v1 is greater than v2.
* The result is 2 if v2 is greater than v1.
* The result is -1 if the version format is unrecognized.
* The result is zero if the strings are equal.
*/

public int VersionCompare(String v1,String v2)
{
int v1Len=StringUtils.countMatches(v1,".");
int v2Len=StringUtils.countMatches(v2,".");

if(v1Len!=v2Len)
{
int count=Math.abs(v1Len-v2Len);
if(v1Len>v2Len)
for(int i=1;i<=count;i++)
v2+=".0";
else
for(int i=1;i<=count;i++)
v1+=".0";
}

if(v1.equals(v2))
return 0;

String[] v1Str=StringUtils.split(v1, ".");
String[] v2Str=StringUtils.split(v2, ".");
for(int i=0;i<v1Str.length;i++)
{
String str1="",str2="";
for (char c : v1Str[i].toCharArray()) {
if(Character.isLetter(c))
{
int u=c-'a'+1;
if(u<10)
str1+=String.valueOf("0"+u);
else
str1+=String.valueOf(u);
}
else
str1+=String.valueOf(c);
}
for (char c : v2Str[i].toCharArray()) {
if(Character.isLetter(c))
{
int u=c-'a'+1;
if(u<10)
str2+=String.valueOf("0"+u);
else
str2+=String.valueOf(u);
}
else
str2+=String.valueOf(c);
}
v1Str[i]="1"+str1;
v2Str[i]="1"+str2;

int num1=Integer.parseInt(v1Str[i]);
int num2=Integer.parseInt(v2Str[i]);

if(num1!=num2)
{
if(num1>num2)
return 1;
else
return 2;
}
}
return -1;
}


Related Topics



Leave a reply



Submit