NateD
NateD

Reputation: 624

How to convert a string into a Point?

I have a list of strings of the format "x,y". I would like to make them all into Points. The best Point constructor I can find takes two ints. What is the best way in C# to turn "14,42" into new Point(14,42);?

I know the Regex for doing that is /(\d+),(\d+)/, but I'm having a hard time turning those two match groups into ints in C#.

Upvotes: 4

Views: 16696

Answers (4)

Tim Hoolihan
Tim Hoolihan

Reputation: 12396

Using Linq this could be a 1-liner

//assuming a list of strings like this
var strings = new List<String>{
   "13,2",
   "2,4"};

//get a list of points
var points = (from s in strings
             select new Point(s.split(",")[0], s.split(",")[1]))
             .ToList();

 // or Point.Parse as PK pointed out
var points = (from s in strings select Point.Parse(s)).ToList();

I'm using a mac to write this, so I can't check syntax, but that should be close.

Upvotes: 1

Paul Kohler
Paul Kohler

Reputation: 2714

There is Point.Parse (System.Windows.Point.Parse, WindowsBase.dll) and then you don't need to mess around with regex or string splitting etc.

http://msdn.microsoft.com/en-us/library/system.windows.point.parse.aspx

PK :-)

Upvotes: 13

SLaks
SLaks

Reputation: 887305

Like this:

string[] coords = str.Split(',');

Point point = new Point(int.Parse(coords[0]), int.Parse(coords[1]));

Upvotes: 12

Annath
Annath

Reputation: 1262

You could use a simple string split using ',' as the delimiter, and then just use int.parse(string) to convert that to an int, and pass the ints into the Point constructor.

Upvotes: 2

Related Questions