我需要从我的项目的文本文件中读取坐标,但文本文件是这样的
1 37.4393516691 541.2090699418
2 612.1759508571 494.3166877396
3 38.1312338227 353.1484581781
并且前面有更多的空间。我有我试过的代码,但我无法使分离器工作。
1 1150.0 1760.0
2 630.0 1660.0
3 40.0 2090.0
代码:
string[] cityPositions = File.ReadAllLines(ofd.FileName);
foreach (string cityP in cityPositions)
{
int startIndexX = cityP.IndexOf(" ", StringComparison.CurrentCultureIgnoreCase) + 3;
int endIndexX = cityP.IndexOf(" ", StringComparison.CurrentCultureIgnoreCase);
int X = int.Parse(cityP.Substring(startIndexX, endIndexX - startIndexX));
int startIndexY = cityP.IndexOf(" ", StringComparison.CurrentCultureIgnoreCase) + 3;
int endIndexY = cityP.IndexOf("", StringComparison.CurrentCultureIgnoreCase);
int Y = int.Parse(cityP.Substring(startIndexY, endIndexY - startIndexY));
create_City(new Point(X, Y));
}
答案 0 :(得分:0)
首先,您的数据类型不匹配。您应该使用double作为坐标,并使用Split方法,例如:
double X = double.Parse(cityP.Split()[1], CultureInfo.InvariantCulture);
double Y = double.Parse(cityP.Split()[2], CultureInfo.InvariantCulture);
没有给出参数的分割函数将按空格分割。
修改强>
在问题中不清楚但是,如果你的线条没有相同的模式,并且有不同的空格,请使用Split方法,如下所示:
double X = double.Parse(cityP.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture);
答案 1 :(得分:0)
如果您想使用正则表达式,请尝试以下方法:
String expression = @"(\d)([\d\.]*)([\d\.]*)";
Regex r = new Regex(expression);
foreach (String cityPosition in cityPositions)
{
MatchCollection mc = r.Matches(cityPosition);
int index = Convert.ToInt32(mc[0].Value);
decimal coOrdX = Convert.ToDecimal(mc[1].Value);
decimal coOrdY = Convert.ToDecimal(mc[2].Value);
Console.WriteLine(String.Format("{0} {1} {2}", index, coOrdX, coOrdY));
}
此代码将生成此输出:
1 1150.0 1760.0
2 630.0 1660.0
3 40.0 2090.0
它应该忽略值之间不同的空间量,并且更容易解析文件中的三个不同值。
答案 2 :(得分:0)
您可以使用单个空格替换多个空格,而不是使用索引,例如
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
cityP = regex.Replace(cityP, " ");
然后使用split来获取坐标
var x = double.Parse(cityP.Split()[1]);
var y = double.Parse(cityP.Split()[2]);