简体   繁体   中英

Parse PointF From String in C#?

Well I have points saved to files that look like this:

PointF p = new PointF(109.1679, 162.4473);
string lineInFile = p.ToString();

// in file it looks like this then:
{X=109,1679, Y=162,4473}

Well I can't use linq nor .NET Framework 4.5 right now. I need a solution pure C# up to 4.0. So how would I parse the point ?

Note that it's PointF not Point and the language specific formatting is making the dot appear as a comma in the string.


Edit: I've accepted an answer but I wished the tiny problem with user modified files would be resolved too. Like { X = 109,1679 ,Y = 162,4473 }

You could use regular expressions to parse the format back again:

using System.Text.RegularExpressions;

Match m = Regex.Match("{X=109,1679, Y=162,4473}", "{X=(\\d+.\\d+), Y=(\\d+.\\d+)}");
PointF p = new PointF(float.Parse(m.Groups[1].Value), float.Parse(m.Groups[2].Value));

Note that I used a . to check for the decimal separator as the output of ToString() will vary depending on locale.

I assume you can't change the file structure of your output file, otherwise you could just use the in-built functions for XML or JSON Serialization.

Here's a string method only version using string.Split and float.TryParse :

string[] tokens = lineInFile.Split(new[]{", "}, StringSplitOptions.RemoveEmptyEntries);
string valueX = tokens[0].Split('=')[1];
string valueY = tokens[1].Split('=')[1].TrimEnd('}');
float x; float y;
if (float.TryParse(valueX, out x) && float.TryParse(valueY, out y))
{
    PointF parsed = new PointF(x, y);
}

Note that it works only if the same NumberDecimalSeparator is used to parse the string to float as used on PointF.ToString .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM