How to convert a string to a point?

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

I know that Regex for this is /(\d+),(\d+)/ , but it's hard for me to turn these two matching groups into ints in C #.

+4
source share
4 answers

Like this:

 string[] coords = str.Split(','); Point point = new Point(int.Parse(coords[0]), int.Parse(coords[1])); 
+10
source

There is Point.Parse (System.Windows.Point.Parse, WindowsBase.dll), and you don't have to bother with a regular expression or section of strings, etc.

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

PK :-)

+11
source

You can use a simple line separator using ',' as the separator, and then just use int.parse(string) to convert this to int and pass the int to the Point constructor.

+2
source

Using Linq, it can 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 use mac to write this, so I can't check the syntax, but it should be close.

+1
source

Source: https://habr.com/ru/post/1308096/


All Articles