C#,在 2 之后拆分;在同一行

标签 c# visual-studio-2010 csv streamreader streamwriter

我正在生成一个起点/终点坐标点列表,以及这些点之间的距离/时间。 例如:最终产品的标题看起来像这样

writer.WriteLine("fromX" + ";" + "fromY" + ";" + "toX" + ";" + "toY" + ";" + "distance" + ";" + "time");

点对点的计算过程如下:

A -> A
A -> B
A -> C
..
B -> A
B -> B
B -> C

等等

距离和时间是预先计算的,位于单独的文件中。但是,此文件中的每一行都包含同一起点和每个终点之间的距离/时间,例如:

0;0;11289;950;9732;899;9886;725;32893;2195;38010;2478;46188;3330;

目标是在最终产品中使用以下符号:

point A;point A;0;0
point A;point B;11289;950
point A;point C;9732;899

等等

如您所见,我需要在每个第二个值处拆分距离 + 时间线。

目前,我有以下代码:

    List<string> locationsList = new List<string>();
    using (var reader = new StreamReader(File.OpenRead("locations.csv")))
    {
        while (reader.Peek() != -1)
            locationsList.Add(reader.ReadLine());
    }

    List<string> distanceTime = new List<string>();
    using (var reader = new StreamReader(File.OpenRead("distance.csv")))
    {
        while (reader.Peek() != -1)
            distanceTime.Add(reader.ReadLine());
    }


    using (var writer = new System.IO.StreamWriter("Output.csv"))
    {
        writer.WriteLine("fromX" + ";" + "fromY" + ";" + "toX" + ";" + "toY" + "distance" + ";" + "time")

        foreach (var fromLine in locationsList)
        {
            splitFrom = fromLine.Split(';');

            fromX = splitFrom[0].Trim();
            fromY = splitFrom[1].Trim();

            foreach (var toLine in locationsList)
            {
                splitTo = toLine.Split(';');

                toX = splitTo[0].Trim();
                toY = splitTo[1].Trim();

                writer.WriteLine(fromX + ";" + fromY + ";" + toX + ";" + toY);
            }

        }

        MessageBox.Show("Done");
    }

这可能必须用 foreach 循环进行扩展,该循环从 distanceTime-list 中读取一行,将其拆分,取前 2 个值并将它们与起点和终点一起写入。 问题是我不知道如何在每个第二个值之后拆分。 你有什么建议吗?

最佳答案

你真的不需要在每一秒';'上拆分,你只需要一个稍微不同的for循环:

using System;

class Program {
    static void Main(string[] args) {
        string line = "0;0;11289;950;9732;899;9886;725;32893;2195;38010;2478;46188;3330;";
        string[] values = line.Split(';');
        char pointName = 'A';
        for (int i = 0; i < values.Length - 1; i += 2) {
            string endProductLine = string.Format("point A;point {0};{1};{2}", pointName, values[i], values[i + 1]);
            Console.WriteLine(endProductLine);
            pointName++;
        }
    }
}

关于C#,在 2 之后拆分;在同一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103100/

相关文章:

c - 将数据添加到结构内部的数组

csv - Logstash-CSV列中的子字符串

c# - 将 xml 转换为排序字典

C# 常量和委托(delegate)

c++ - 错误 LNK2019 : unresolved external symbol linker can't find dll

python - 用 Pandas 读取格式错误的 'csv' 文件

powershell - 尝试为 Active Directory 运行 PowerShell 脚本时出现错误解析错误

c# - POS机与银行之间的支付

javascript - C# 和 Javascript 中的正则表达式

c++ - 在 MFC 中更改 listcntrl 的方向时出错