如何将字符串数组中的数字解析为int数组c#

时间:2016-04-18 18:32:29

标签: c# arrays parsing methods

这是我的一个问题。我可以让for循环读入数组,但它不会将元素存储在新数组中。这里的任何帮助将不胜感激!!!!

static void parse()
    {

        StreamReader sr = new StreamReader("sales.txt");

        //variables declared here
        string line = "";
        double mean = 0;
        double sum = 0.0;
        int count = 0;

        double answer = 0;

        double[] numbersTwo = new double[10];


        while loop that reads in the .txt file

        while ((line = sr.ReadLine()) != null)
        {
            if (line != null)
            {
                string[] detailsArray = line.Split(',');

                for (int i = 0; i < detailsArray.Length; i++)
                {

                    int number = 0, parseOne = 0;

                    parseOne = int.Parse(detailsArray[3]);
                    numbersTwo[number] = parseOne;
                    //number++;
                }
            }
        }
    }

3 个答案:

答案 0 :(得分:0)

试试这个

int[] numbersTwo = new int[10];


while ((line = sr.ReadLine()) != null)
    {
        if (line != null)
        {
            string[] detailsArray = line.Split(',');

            for (int i = 0; i < detailsArray.Length; i++)
            {                
                numbersTwo[i] = Convert.ToInt32(detailsArray[i]);
            }
        }
    }

答案 1 :(得分:0)

为什么是阵列?
如果你真的需要一个数组,那么只需从最后的List中创建它

static void parse()
{
    StreamReader sr = new StreamReader("sales.txt");
    //variables declared here
    string line = string.empty;
    double answer = 0;
    List<double> numbersTwo = new List<double>();
    //while loop that reads in the .txt file
    while ((line = sr.ReadLine()) != null)
    {
        if (line != null)
        {
            foreach (string num in line.Split(',');)
            {
                numbersTwo.Add(double.Parse(num));
            }
        }
    }
}

如果失败,您可能希望使用TryParse

if (double.TryParse(num, answer))
   numbersTwo.Add(answer);

答案 2 :(得分:0)

您始终在与结果数组的第一个元素相同的位置添加数字。我相信实现你想要的最优雅的方法是在Linq中使用这几行:

var numbers = File.ReadAllLines("sales.txt")
    .SelectMany(line => line.Split(","), (line, elem) => int.Parse(elem))
    .ToArray();