问题描述:

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

网友答案:

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());
}
网友答案:

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]));
                   }))
网友答案:

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();
}
网友答案:

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);
相关阅读:
Top