【问题标题】:How can I convert a text file into a list of int arrays如何将文本文件转换为 int 数组列表
【发布时间】:2014-01-25 07:23:53
【问题描述】:

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

0 0 1 0 3 
0 0 1 1 3 
0 0 1 2 3 
0 0 3 0 1 
0 0 0 1 2 1 1 
0 0 1 0 3 
0 0 1 1 3 
0 0 1 2 3 
0 0 3 0 1 
0 0 1 2 3 
0 0 3 0 1

行之间没有空格,但数字之间有空格。我想从 txt 文件中读取这些整数并保存在 C# 中的 int 数组列表中。

【问题讨论】:

  • 行是如何分开的?有换行吗?或者更确切地说是一个长长的数字数组,由编辑器在视觉上包装?
  • txt 文件看起来是这样的,确实没有。行数

标签: c# arraylist text-files


【解决方案1】:

假设您的字符串称为文本,并且包含“1 1 1 0 3 2 3”等。 你声明一个字符串数组。

String[] numbers1=text.Split(" ");

现在声明您的 int 数组并将每个数组转换为 int。

int[] numbers2=new int[numbers.Length];
for(int i=0; i<numbers.Length; i++)
    numbers2[i]=Convert.ToInt32(numbers1[i]);

你已经完成了。

【讨论】:

  • 这一切都可以在一条线上int[] arr= text.Split(' ').Select(n =&gt; Convert.ToInt32(n)).ToArray();。并且 Split 没有重载方法只接受字符串参数。它应该是字符。
  • 没听懂,你说的花时间是什么意思,需要多少时间?
【解决方案2】:

这对我有用:

var numbers =
    System.IO.File
        .ReadAllLines(@"C:\text.txt")
        .Select(x => x.Split(' ')
            .Select(y => int.Parse(y))
            .ToArray())
        .ToList();

我得到这个结果:

【讨论】:

    【解决方案3】:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace FileToIntList
    {
    class Program
    {
        static void Main(string[] args)
        {
            // Read the file as one string.
            System.IO.StreamReader myFile =
               new System.IO.StreamReader("C:\\Users\\M.M.S.I\\Desktop\\test.txt");
            string myString = myFile.ReadToEnd();
    
            myFile.Close();
    
            // Display the file contents.
            //Console.WriteLine(myString);
            char rc = (char)10;
            String[] listLines = myString.Split(rc);
            List<List<int>> listArrays = new List<List<int>>();
            for (int i = 0; i < listLines.Length; i++)
            {
                List<int> array = new List<int>();
                String[] listInts = listLines[i].Split(' ');
                for(int j=0;j<listInts.Length;j++)
                {
                    if (listInts[j] != "\r")
                    {
                        array.Add(Convert.ToInt32(listInts[j]));
                    }
                }
                listArrays.Add(array);
            }
    
    
            foreach(List<int> array in listArrays){
                foreach (int i in array)
                {
                    Console.Write(i + " ");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
    
    
        }
    }
    }
    

    【讨论】:

    • 行在listArrays中,listArrays的每个元素都是你的文本文件的一行。
    • 抱歉耽误您的时间,但我需要帮助,我想要这个结果列表{[0,0,1,0,3][0,0,1,1,3]} List[] 输出
    • @user2680386 这会将整个文件读入内存,如果文件很大,这不是一个好主意。
    • 这个程序返回你想要的结果列表,它是一个int Lists的列表
    • 这是我第一次用 c# 编程,所以我的项目遇到了困难
    【解决方案4】:
    var resultList = new List<int>();
    File.ReadAllLines("filepath") 
        .ToList()
        .ForEach((line) => {
                                var numbers = line.Split()
                                                  .Select(c => Convert.ToInt32(c));
                                resultList.AddRange(numbers); 
                            });
    

    【讨论】:

    • Split() 没有采用零参数的重载。
    • @phoog,你错了。看这个:msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspxIf the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters.
    • @Selman22 当然。我忘记了 Split(char[]) 重载的参数是 params 数组。但我注意到,在我写完评论后,您将 c =&gt; (int)c(这是一个编译错误)更改为 Convert.ToInt32 调用。也许更重要的是,如果你使用Select,整个事情会更简洁。
    【解决方案5】:
    using System.IO;
    using System.Linq;
    
    string filePath = @"D:\Path\To\The\File.txt";
    List<int[]> listOfArrays =
        File.ReadLines(path)
        .Select(line => line.Split(' ').Select(s => int.Parse(s)).ToArray())
        .ToList();
    

    既然你提到这是你第一次用C#编程,这个版本可能更容易理解;过程同上:

    using System.IO;
    using System.Linq;
    
    string filePath = @"D:\Path\To\The\File.txt";
    
    IEnumerable<string> linesFromFile = File.ReadLines(path);
    
    Func<string, int[]> convertStringToIntArray =
        line => {
            var stringArray = line.Split(' ');
            var intSequence = stringArray.Select(s => int.Parse(s)); // or ....Select(Convert.ToInt32);
            var intArray = intSequance.ToArray();
            return intArray;
        };
    
    IEnumerable<int[]> sequenceOfIntArrays = linesFromFile.Select(convertStringToIntArray);
    
    List<int[]> listOfInfArrays = sequenceOfIntArrays.ToList();
    

    【讨论】:

    • 错误 1 ​​方法 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' 的类型参数不能从用法中推断出来。尝试明确指定类型参数。 C:\C#\ConsoleApplication4\ConsoleApplication4\Program.cs 27 21 ConsoleApplication4 我有这个错误
    猜你喜欢
    • 1970-01-01
    • 2020-03-13
    • 2016-04-14
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    相关资源
    最近更新 更多