1

I'm trying to figure out how to compare two strings (Numbers and Multiple Decimals) to see what one is greater numerically.

One string is version information read from the registry being compared against a string value read from a XML file.

This example can simulate what I'm trying to do though. Lets say string One variable is the string variable I read from the registry and string Two variable from the XML.

Dim One As String = "10.0.0.0"
Dim Two As String = "2.0.0.0"

If Two >= One Then MsgBox("Greater") Else MsgBox("Smaller")

The following code won't compare correctly since these are strings and the string comparison see's 10 as less than 2 although 10 is really greater than 2.

I've tried doing some integer conversion to no luck appears the decimals are causing issues.

Does anyone know how this could be converted to a number/integer so that we can convert the strings somehow so 10.0.0.0 would be seen as greater than 2.0.0.0?

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
JustinTime
  • 11
  • 6

1 Answers1

1

Your strings look like they may be version codes. In which case you may want to treat them differently than simply as integers. For integers:

Dim str1 = "10.0.0.0"
Dim str2 = "2.0.0.0"
Dim str3 = "10.0.0.1"

Dim n1 = Convert.ToInt32(str1.Split("."c)(0))
Dim n2 = Convert.ToInt32(str2.Split("."c)(0))

After splitting the strings on ".", the first element is converted to integer so that n1 will be 10 and n2 will be 2 allowing you to compare them directly.

If they do represent versions, such as str1 vs str3, you can end up with multiple tests to check each sub segment.

.NET includes a Version Type for just such things:

Dim v1 As New Version(str1)
Dim v2 As New Version(str3)

If v1 > v2 Then
   ' first ver is larger
Else
   ' str3 contains larger ver
End If

There is no need to test Major/Minor/Build/Revision parts individually -- the Type does all that for you. Incidentally, once you have a valid Version variable, you can create a string in that same format using ToString():

Console.WriteLine("The Version is: '{0}'", v2.ToString())

Result:

The Version is: '10.0.0.1'

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
  • Thanks a lot this is looking good. There are a few apps that are being read that may only contain a single value like 3 for example in this case if obviously fails to set the string as a version would you suggest a try statement for something like this? – JustinTime Mar 13 '15 at 04:27
  • if it is *not* actually a version string, I might not use `Version` - in that case parse the string using Split but maybe do that in a class which exposes the parts in a way that makes compares easy. – Ňɏssa Pøngjǣrdenlarp Mar 13 '15 at 04:44