Alexander.It
Alexander.It

Reputation: 187

c# catching a Point type from string

I send through a NetworkStream a string with points formatted in this way:

(x,y)(x,y)(x,y)(x,y)

i want to reconvert this string in an array of System.Drawing.Point. How can i do?

thanks for help

Upvotes: 0

Views: 231

Answers (4)

Matthew Haugen
Matthew Haugen

Reputation: 13286

You can use a regex, then parse the strings, all in LINQ.

string args = "(4,1)(7,5)(5,4)(2,3)"; // Test data

return Regex.Matches(args, @"\(([^)]*)\)")
            .Cast<Match>()
            .Select(c => 
                   {
                       var ret = c.Groups[1].Value.Split(',');
                       return new Point(int.Parse(ret[0]), int.Parse(ret[1]));
                   }))

Upvotes: 2

Sergey Mozhaykin
Sergey Mozhaykin

Reputation: 192

You can try parse it using Regex:

string str = @"(11,22)(2,3)(4,-10)(5,0)";
Regex r = new Regex(@"(-?[0-9]+),(-?[0-9]+)");
Match m = r.Match(str);
var points = new List<System.Drawing.Point>();
while (m.Success)
{
    int x, y;
    if (Int32.TryParse(m.Groups[1].Value, out x) && Int32.TryParse(m.Groups[2].Value, out y))
    {
        points.Add(new System.Drawing.Point(x, y));
    }
    m = m.NextMatch();
}

Upvotes: 1

Alfredo Alvarez
Alfredo Alvarez

Reputation: 334

My attempt at parsing it:

        string s = "(1,2)(2,3)(3,4)(4,5)";

        var rawPieces = s.Split(')');

        var container =  new List<System.Drawing.Point>();
        foreach(var coordinate in rawPieces)
        {
            var workingCopy = coordinate.Replace("(",String.Empty).Replace(")",String.Empty);
            if(workingCopy.Contains(","))
            {
                var splitCoordinate = workingCopy.Split(',');
                if(splitCoordinate.Length == 2)
                {
                    container.Add(new System.Drawing.Point(Convert.ToInt32(splitCoordinate[0]),Convert.ToInt32(splitCoordinate[1])));
                }
            }
        }

        Console.WriteLine(container.Count);

Upvotes: 0

Mehdi Khademloo
Mehdi Khademloo

Reputation: 2812

You can use the Regex on this way

string S = "(1,2)(33,44)(55,66)(77,8888)";
Regex R = new Regex(@"\((\d|\,)+\)");
foreach (Match item in R.Matches(S))
{
    var P = item.Value.Substring(1,item.Value.Length-2).Split(',');
    Point YourPoint = new Point(int.Parse(P[0]), int.Parse(P[1]));
    MessageBox.Show(YourPoint.ToString());
}

Upvotes: 1

Related Questions