[英]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. 好吧,我现在不能使用linq和.NET Framework 4.5。 I need a solution pure C# up to 4.0. 我需要一个纯C#的解决方案,最高可达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. 请注意,它是PointF
而不是Point
并且特定于语言的格式设置使点在字符串中显示为逗号。
{ X = 109,1679 ,Y = 162,4473 }
像{ 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. 检查小数分隔符,因为ToString()
的输出将根据区域设置而变化。
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. 我假设您无法更改输出文件的文件结构,否则您可以使用内置函数进行XML或JSON序列化。
Here's a string method only version using string.Split
and float.TryParse
: 这是使用string.Split
和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
. 请注意,只有在PointF.ToString
上使用相同的NumberDecimalSeparator
将字符串解析为float时,它才PointF.ToString
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.