Sergey
Sergey

Reputation: 189

Best way to break a string on the penultimate dot on C#

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

Answers (5)

Chris Leyva
Chris Leyva

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

Rodrigo Silva
Rodrigo Silva

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

Habib
Habib

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

briba
briba

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

L.B
L.B

Reputation: 116178

Something like this?

var newstr = String.Join(".", "1.2.3.4".Split('.').Take(2));

Or maybe you want to use the Version class

var ver = new Version("1.2.3.4");
Console.WriteLine(ver.Major + "." + ver.Minor);

Upvotes: 8

Related Questions