Reputation: 11
I have a text file containing the following content:
0 12
1 15
2 6
3 4
4 3
5 6
6 12
7 8
8 8
9 9
10 13
There are no spaces between two rows but there is a space between two numbers. I want to read these integers from a txt file and save the two columns into two different arrays in C#.Cn anyone help
Upvotes: 0
Views: 7221
Reputation: 100238
Try the following:
var r = File.ReadAllLines(path)
.Select(line => line.Split(' '))
.Select(arr => new
{
Column0 = Int32.Parse(arr[0]),
Column1 = Int32.Parse(arr[1])
// etc
})
.ToArray();
Then:
int[] column0 = r.Select(x => x.Column0).ToArray(); // note double loop over r
int[] column1 = r.Select(x => x.Column1).ToArray();
or more long but also more efficient:
int[] column0 = new int[r.Length], column1 = new int[r.Length];
for (int i = 0; i < r.Length; i++) // single loop over r
{
column0[i] = t[i].Column0;
column1[i] = t[i].Column1;
}
or even more long but also even more efficient (general speaking):
List<int> column0 = new List<int>(), column1 = new List<int>();
using (Stream stream = File.Open(path, FileMode.Open))
using (TextReader sr = new StreamReader(stream, Encoding.UTF8))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] arr = line.Split(' ');
column0.Add(Int32.Parse(arr[0]);
column1.Add(Int32.Parse(arr[1]);
}
}
To iterate/display result (zero index based, i.e. line 0, 1, etc.):
for (int i = 0; i < column0.Length; i++)
{
Console.WriteLine("Line {0}: column 0: {1}, column 1: {2}", i, column0[i], column1[i]);
}
For better reliability, use a function instead of Int32.Parse:
static int Parse(string input)
{
int i;
if (!Int32.TryParse(intput, out i)
throw new Exception("Can't parse " + input);
return i;
}
Upvotes: 2
Reputation: 490
You can check the following code as well..
string data = string.Empty;
List<int[]> intarray = new List<int[]>();
void ReadData()
{
data = File.ReadAllText("Input.txt");
}
List<int[]> Getdata()
{
string[] lines = data.Split('\n', '\r');
foreach (string line in lines)
{
if(!string.IsNullOrEmpty(line.Trim()))
{
int[] intdata = new int[2];
string[] d = line.Split(' ');
intdata[0] = Convert.ToInt32(d[0]);
intdata[1] = Convert.ToInt32(d[1]);
intarray.Add(intdata);
intdata = null;
}
}
return intarray;
}
Upvotes: 0