2014-09-27 47 views
0

捉點型我通過NetworkStream發送一個字符串以這種方式格式化分:C#從字符串

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

我想在System.Drawing.Point數組重新轉換此字符串。 我該怎麼辦?

感謝您的幫助

+0

這是一個**究竟語法**? – 2014-09-27 18:49:06

+0

@TheZenCoder這將與System.Windows.Point,但不是System.Drawing.Point。 http://stackoverflow.com/a/10366671/1174581 – 2014-09-27 19:10:14

回答

1

您可以在這條路上

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()); 
} 
2

您可以使用正則表達式使用Regex,然後解析字符串,都在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])); 
        })) 
+0

什麼是'args'? – 2014-09-27 19:06:58

0

我在解析它的嘗試:

 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); 
1

您可以嘗試解析它使用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(); 
}