-3

I am using C# and I have a string with the values like strResult = "(30,40),(189,339),(30,40),(60,30)". I wanted to convert these value into System.Windows.Point . so that 1st value of point[0].x = 30 ,point[0].y = 40 and so on.

{
 string[] numbers = System.Text.RegularExpressions.Regex.Split(strResult, @"[(),]+");
  for (int i = 0; i < numbers; i++)
  { 
   System.Windows.Point point = // do something
   drawingContext.DrawEllipse(Brushes.Green, null, new System.Windows.Point(point.X, point.Y), 3, 3);
  }

Can anyone help on this ? Thanks in advance :)

Miki
  • 40,887
  • 13
  • 123
  • 202

2 Answers2

0

Parsing strings into ints can be done with Convert.ToInt32 or Int32.Parse (or many other options).

Be careful with your regex. That particular code will return array with empty first and last elements: "", "30", "40", ..., "60", "30", "" .

You can parse 2 elements for single point in each iteration. I handled first and last empty elements but it would be better to rewrite regex properly:

    for (int i = 1; i < numbers.Length - 1; i += 2)
    {       
       System.Windows.Point point = new System.Windows.Point(Convert.ToInt32(numbers[i]), Convert.ToInt32(numbers[i + 1])); 
       drawingContext.DrawEllipse(Brushes.Green, null, new System.Windows.Point(point.X, point.Y), 3, 3);
    }
Sergio
  • 65
  • 1
  • 5
0

Here is a more appropriate regex expression for your scenario: \((.*?)\)

This will provide you with an array of all the points as x, y. Now you just have to split the string by , and trim the results. Finally, loop through the point array and create a new point with parsed int values.

    var pointString = "(30,40),(189,339),(30,40),(60,30)";
    var ps = Regex.Split(pointString, @"\((.*?)\)");
    foreach (var p in ps) {
        if (!string.IsNullOrEmpty(p)) {
            var px = p.Split(',');
            var x = int.Parse(px[0].Trim());
            var y = int.Parse(px[1].Trim());
            var point = new Point(x, y);
            Console.WriteLine(point);
        }
    }