将文本文件拆分为2D数组 [英] Splitting text file into 2D array

查看:56
本文介绍了将文本文件拆分为2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要拆分为2D数组的文本文件

this is the text file that i want to split into a 2D array

"YHOO",36.86,21,13873900,37.00"GOOG",684.11,1114,1821650,686.72"MSFT",50.54,3993,31910300,50.65"AAPL",94.40,28201,39817000,94.26

这是我为实现此目的而实现的代码,

and this is the code I have implemented to do this but it won't work

 String input = File.ReadAllText(@"..\..\Data\stockInfo.txt");

        int i = 0, j = 0;
        string[,] result = new string[3, 5];
        foreach (var row in input.Split('\n'))
        {
            j = 0;
            foreach (var col in row.Trim().Split(','))
            {
                result[i, j] = string.Parse(col.Trim());
                j++;
            }
            i++;
        }

推荐答案

数组大小错误.另外,您不需要string.Parse,因为Split的输出是IEnumerable的字符串

The size of array was wrong. Also, you don't need to string.Parse, as output of Split is IEnumerable of strings

int i = 0, j = 0;
string[,] result = new string[4, 5];
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(','))
    {
        result[i, j] = col.Trim();
        j++;
    }
    i++;
}

这篇关于将文本文件拆分为2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆