I have a text file containing the following content:
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
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();
}
}
}
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();
Since you mention that it is your first time programming in C#, this version may be easier to understand; the process is the same as the above:
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();
var resultList = new List<int>();
File.ReadAllLines("filepath")
.ToList()
.ForEach((line) => {
var numbers = line.Split()
.Select(c => Convert.ToInt32(c));
resultList.AddRange(numbers);
});
Let's say your string is called text, and contains "1 1 1 0 3 2 3" etc. You declare a string array.
String[] numbers1=text.Split(" ");
Now declare your int array and convert each one to int.
int[] numbers2=new int[numbers.Length];
for(int i=0; i<numbers.Length; i++)
numbers2[i]=Convert.ToInt32(numbers1[i]);
And you're done.
This works for me:
var numbers =
System.IO.File
.ReadAllLines(@"C:\text.txt")
.Select(x => x.Split(' ')
.Select(y => int.Parse(y))
.ToArray())
.ToList();
I get this result: