5

If I have a version number that has 5 digits such as "1.0.420.50.0", how could I truncate this number (and other version numbers like "1.0.512.500.0") to only 4 digits? "1.0.420.50.0" --> "1.0.420.50"

I would prefer to use an array but any other methods work too! Thanks for any advice in advance!

1
  • 2
    var newString = String.Join(".", oldString.Split('.').Take(4)); Commented Aug 6, 2015 at 18:51

3 Answers 3

8

I haven't programmed in c# in a while so the syntax may be off. If the versioning can be more than six digits, you won't want a method that relies on removing the last digit. Instead just take the first four version numbers.

String version = "1.0.420.50.0"; String [] versionArray = version.Split("."); var newVersion = string.Join(".", versionArray.Take(4)); 
Sign up to request clarification or add additional context in comments.

3 Comments

You could do var newVersion = string.Join(".", versionArray.Take(4)); instead. That would work even if the original has less than 4.
You don't need that last line now as string.Join doesn't add a trailing delimiter.
@juharr Thanks! I wasn't aware of string.Join.
0

If it's a string, you could do something like

ver = "1.2.3.4.5"; ver = ver.substring(0, ver.lastindexof("."); 

this should give you all the way up to the last ".". This is not very robust if your version numbers get longer or shorter, but it would work for a 5 digit version number. This is also the basic idea you want if you have a string.

Comments

0

Get the index of the last period and then get the substring from index 0 to the index of the last period. EX:

string version = "1.0.420.50.0"; int lastPeriodIndex = version.LastIndexOf('.'); string reformattedVersion = version.Substring(0, lastPeriodIndex); 

through using an array, if that's what you really want:

string version = "1.0.420.50"; var numbers = version.Split(new char[]{'.'}, StringSplitOptions.RemoveEmptyEntries); string reformattedVersion = numbers[0] + '.' + numbers[1] + '.' + numbers[2] + '.' + numbers[3]; 

but that's a much less elegant/quick solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.