Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将文本文件拆分为c#中带有分隔符的二维数组?_C#_Arrays_Text Files_Delimiter - Fatal编程技术网

如何将文本文件拆分为c#中带有分隔符的二维数组?

如何将文本文件拆分为c#中带有分隔符的二维数组?,c#,arrays,text-files,delimiter,C#,Arrays,Text Files,Delimiter,我的文本文件包含以下内容: 2018年1月1日;0;29;10 1/2/2018;0;16;1. 1/3/2018;0;32;1. 1/4/2018;0;34;15 1/5/2018;0;19;2. 1/6/2018;0;21;2. 在文本文件的下面是小数,这就是为什么我尝试使用double 1/29/2018;0.32;52;38 1/30/2018;0.06;44;21 我正在尝试拆分分号,并将分号之间的每个值分配到一个包含31行和4列的二维数组中 private void button

我的文本文件包含以下内容:

2018年1月1日;0;29;10
1/2/2018;0;16;1.
1/3/2018;0;32;1.
1/4/2018;0;34;15
1/5/2018;0;19;2.
1/6/2018;0;21;2.
在文本文件的下面是小数,这就是为什么我尝试使用double

1/29/2018;0.32;52;38
1/30/2018;0.06;44;21
我正在尝试拆分分号,并将分号之间的每个值分配到一个包含31行和4列的二维数组中

private void button1_Click(object sender, EventArgs e)
{
    // 2d array
    double[,] testarray = new double[31, 4];
    string inputFile = File.ReadAllText("testywesty.txt");
    char[] spearator = {';',' '};

    for (int row = 0; row < 31; row++)
    {
        for (int column = 0; column < 4; column++)
        {
            string[] strlist = inputFile.Split(spearator);
            testarray [row,column] = double.Parse(strlist[column]);
        }
    }
}
private void按钮1\u单击(对象发送者,事件参数e)
{
//二维阵列
double[,]testarray=新的double[31,4];
字符串inputFile=File.ReadAllText(“testywesty.txt”);
char[]spearator={';','};
对于(int行=0;行<31;行++)
{
for(int列=0;列<4;列++)
{
字符串[]strlist=inputFile.Split(spearator);
testarray[row,column]=double.Parse(strlist[column]);
}
}
}
我相信我有正确的循环需要将我的值插入到2d数组中,但是,我的输入有一个错误,我相信这是因为斜杠


我的代码是否足以将文本文件的内容保存到数组中?如何处理
'/'
字符?

您可能会在斜杠上遇到错误,因为您试图将它们转换为双精度字符,这是不可能的。您可以做的一件事是首先使用该类的
Parse
方法将它们转换为
DateTime
,然后使用
ToOADate
方法将其转换为
double
。请注意,如果需要将其转换回,可以使用
DateTime.FromOADate
方法,正如我在下面的输出中所做的那样

此外,使用
File.ReadAllLines
将文件读入字符串数组可能会有所帮助,其中每个字符串都是一个文件行(假设每行包含您需要的四个部分,如问题中的示例文件内容所示)。这样,每一行表示一行,然后我们可以拆分该行以获得列

例如:

private static void button1_Click(object sender, EventArgs e)
{
    var lines = File.ReadAllLines("testywesty.txt");
    var items = new double[lines.Length, 4];
    var delims = new[] {';', ' '};

    for (var line = 0; line < lines.Length; line++)
    {
        var parts = lines[line].Split(delims);
        var maxParts = Math.Min(parts.Length, items.GetLength(1));

        for (var part = 0; part < maxParts; part++)
        {
            if (part == 0)
            {
                // Parse first item to a date then use ToOADate to make it a double
                items[line, part] = DateTime.Parse(parts[part]).ToOADate();
            }
            else
            {
                items[line, part] = double.Parse(parts[part]);
            }
        }
    }

    // Show the output
    var output = new StringBuilder();
    for (var row = 0; row < items.GetLength(0); row++)
    {
        var result = new List<string>();
        for (var col = 0; col < items.GetLength(1); col++)
        {
            result.Add(col == 0
                ? DateTime.FromOADate(items[row, col]).ToShortDateString()
                : items[row, col].ToString());
        }

        output.AppendLine(string.Join(", ", result));
    }
    MessageBox.Show(output.ToString(), "Results");
}
private static void按钮1\u单击(对象发送者,事件参数e)
{
var lines=File.ReadAllLines(“testywesty.txt”);
var项目=新的双精度[lines.Length,4];
var delims=new[]{';','};
用于(变量行=0;行<行.长度;行++)
{
var parts=行[line].拆分(delims);
var maxParts=Math.Min(parts.Length,items.GetLength(1));
对于(var part=0;part
输出


当然,您可以读取数据并将其解析为数组。但是由于它是多态的,所以数组需要是
object[,]
类型。我会这样做:

class Program
{

    static void Main(string[] args)
    {
        object[,] array = ReadFileAsArray("testywesty.txt");            
    }

    static object[,] ReadFileAsArray(string file)
    {
        // how long is the file?
        // read it twice, once to count the rows 
        // and a second time to read each row in
        int rows = 0;

        var fs = File.OpenText(file);
        while (!fs.EndOfStream)
        {
            fs.ReadLine();
            rows++;
        }
        fs.Close();

        var array = new object[rows, 4];
        fs = File.OpenText(file);
        int row = 0;
        while (!fs.EndOfStream)
        {
            // read line
            var line = fs.ReadLine();
            // split line into string parts at every ';'
            var parts = line.Split(';');
            // if 1st part is date store in 1st column
            if (DateTime.TryParse(parts[0], out DateTime date))
            {
                array[row, 0] = date;
            }
            // if 2nd part is flaot store in 2nd column
            if (float.TryParse(parts[1], out float x))
            {
                array[row, 1] = x;
            }
            // if 3rd part is integer store in 3rd column
            if (int.TryParse(parts[2], out int a))
            {
                array[row, 2] = a;
            }
            // if 4rd part is integer store in 4rd column
            if (int.TryParse(parts[3], out int b))
            {
                array[row, 3] = b;
            }
            row++;
        }
        fs.Close();

        return array;
    }
}
但我觉得这太笨重了。如果文件所表示的数据类型是预先确定的,则在
C#
中填充自定义类型的集合会感觉更自然,因为您让该类型处理自己的数据和解析。考虑下面的例子:

class Program
{

    static void Main(string[] args)
    {
        IEnumerable<MyData> list = ReadFileAsEnumerable("testywesty.txt");

        Debug.WriteLine(MyData.ToHeading());
        foreach (var item in list)
        {
            Debug.WriteLine(item);
        }            
        // date        x    a    b   
        // 1/1/2018       0   29   10
        // 1/2/2018       0   16    1
        // 1/3/2018       0   32    1
        // 1/4/2018       0   34   15
        // 1/5/2018       0   19    2
        // 1/6/2018       0   21    2
        // 1/29/2018   0.32   52   38
        // 1/30/2018   0.06   44   21
    }

    public static IEnumerable<MyData> ReadFileAsEnumerable(string file)
    {
        var fs = File.OpenText(file);
        while (!fs.EndOfStream)
        {
            yield return MyData.Parse(fs.ReadLine());
        }
        fs.Close();
    }
}

/// <summary>
/// Stores a row of my data
/// </summary>
/// <remarks>
/// Mutable structures are evil. Make all properties read-only.
/// </remarks>
public struct MyData
{
    public MyData(DateTime date, float number, int a, int b)
    {
        this.Date = date;
        this.Number= number;
        this.A=a;
        this.B=b;
    }
    public DateTime Date { get; }
    public float Number { get; }
    public int A { get; }
    public int B { get; }

    public static MyData Parse(string line)
    {
        // split line into string parts at every ';'
        var parts = line.Split(';');
        // if 1st part is date store in 1st column
        if (DateTime.TryParse(parts[0], out DateTime date)) { }
        // if 2nd part is flaot store in 2nd column
        if (float.TryParse(parts[1], out float number)) { }
        // if 3rd part is integer store in 3rd column
        if (int.TryParse(parts[2], out int a)) { }
        // if 4rd part is integer store in 4rd column
        if (int.TryParse(parts[3], out int b)) { }

        return new MyData(
            date,
            number,
            a,
            b);
    }
    public static string ToHeading()
    {
        return $"{"date",-11} {"x",-4} {"a",-4} {"b",-4}";
    }
    public override string ToString()
    {
        return $"{Date.ToShortDateString(),-11} {Number,4} {A,4} {B,4}";
    }
}
类程序
{
静态void Main(字符串[]参数)
{
IEnumerable list=ReadFileAsEnumerable(“testywesty.txt”);
Debug.WriteLine(MyData.ToHeading());
foreach(列表中的变量项)
{
调试写入线(项目);
}            
//日期x a b
// 1/1/2018       0   29   10
// 1/2/2018       0   16    1
// 1/3/2018       0   32    1
// 1/4/2018       0   34   15
// 1/5/2018       0   19    2
// 1/6/2018       0   21    2
// 1/29/2018   0.32   52   38
// 1/30/2018   0.06   44   21
}
公共静态IEnumerable ReadFileAsEnumerable(字符串文件)
{
var fs=File.OpenText(文件);
而(!fs.EndOfStream)
{
返回MyData.Parse(fs.ReadLine());
}
fs.Close();
}
}
/// 
///存储一行我的数据
/// 
/// 
///可变结构是邪恶的。将所有属性设置为只读。
/// 
公共结构MyData
{
公共MyData(日期时间日期、浮点数、整数a、整数b)
{
这个日期=日期;
这个。数字=数字;
这个A=A;
这个.B=B;
}
公共日期时间日期{get;}
公共浮点数{get;}
公共int A{get;}
公共int B{get;}
公共静态MyData解析(字符串行)
{
//在每个“;”处将线拆分为字符串部分
var parts=line.Split(“;”);
//如果第一部分是日期,则在第1列中存储
if(DateTime.TryParse(parts[0],out DateTime date)){}
//如果第二部分是flaot,则将其存储在第二列中
if(float.TryParse(parts[1],out float number)){}
//如果第三部分是整数,则存储在第三列中
if(int.TryParse(parts[2],out int a)){}
//如果第4部分是整数,则存储在第4列中
if(int.TryParse(parts[3],out int b)){}
返回新的MyData(
日期,
数字,
A.
b) );
}
公共静态字符串ToHeading()
{
返回$“{”date“,-11}{”x“,-4}{”a“,-4}{”b“,-4