Reputation: 189
Need to get substring from string from "1.2.3.4" to "1.2" I have this solution:
string version = "1.2.3.4";
var major = version.Substring(0, version.Substring(0, version.LastIndexOf('.')).LastIndexOf('.'));
but it looks ugly. what would be the best way to do this? (note) initial string may be with different size like 11.22.33.44 or other
Upvotes: 1
Views: 364
Reputation: 3526
Well, here's another way to do it. Though you should probably use the Version
class.
string version = "1.2.3.4";
int indexOfFirstDot = version.IndexOf('.', 0);
int indexOfSecondDot = version.IndexOf('.', indexOfFirstDot+1);
string majorAndMinorVersion = version.Substring(0, indexOfSecondDot);
Upvotes: 0
Reputation: 432
I like to use regex for these kind of parsing:
string version = "1.2.3.4";
string sub = Regex.Match(version, @"[1-9].[1-9]").ToString();
Upvotes: 0
Reputation: 223352
Consider using Version
class:
string version = "1.2.3.4";
Version ver = new Version(version);
And then you can combine Major
and Minor
var major = string.Format("{0}.{1}", ver.Major, ver.Minor);
That would give you "1.2"
Upvotes: 2
Reputation: 2987
How about this?
string version = "1.2.3.4";
int pos1 = version.IndexOf(".");
if (pos1 >= 0)
{
pos1++;
int pos2 = version.IndexOf(".", pos1);
if (pos2 >= 0)
{
version = version.Substring(0, pos2);
}
}
Upvotes: 0