Splitting text file into 2D array - c#

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++;
}

Jagged array String[][] (array of array) is often more flexible than 2D one String[,]:
string[][] result = File
.ReadLines(#"..\..\Data\stockInfo.txt")
.Select(line => line.Split(','))
.ToArray();
If you insist on 2D array you have to put less efficient code
string[] lines = File.ReadAllLines(#"..\..\Data\stockInfo.txt");
string[,] result = null;
for (int i = 0; i < lines.Count; ++i) {
string[] items = lines.Split(',');
if (null == result)
result = new string[lines.Count, items.Length];
for (int j = 0; j < items.Length; ++j)
result[i, j] = items[j];
}

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++;
}

Related

I want to read a table from text file and assign each column to an array

i want to store each row in a different array. below is the code i tried.
but it doesn't not work, it only splits the last line and store values in "valueperline" array
first 11 rows are source text. file and screen shot of console
using System;
using System.Collections.Generic;
using System.IO;
namespace BBS_optimize
{
class Program
{
static void Main()
{
int i = 0; int j = 0; int k =0; string[] valueperline = new string[0]; string[] lines = new string [0];
lines = File.ReadAllLines("Table1.txt");
for (i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (j = 0; j<lines.Length; j++)
{ valueperline = lines[j].Split('\t');
}
for (k = 0; k < 44; k++)
{ Console.WriteLine(valueperline[k]);
}
}
}
}
Use array:
string[,] ParseFromFile (string fileName)
{
// Assume that your table have 10 cols and 100 rows
string[,] result = new string[10,100];
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
string[] row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries);
result[i] = row;
}
return result;
}
Use List:
List<List<string>> ParseFromFile (string fileName)
{
// Your list
List<List<string>> result = new List<List<string>>();
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
List<string> row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries).ToList();
result.Add(row);
}
return result;
}
below is a solution:
static void Main(string[] args)
{
List<List<string>> lst = new List<List<string>>();
string[] lines = new string[0];
lines = File.ReadAllLines("tableX.txt");
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (int j = 0; j < lines.Length; j++)
{
var line = lines[j].Split(' ').ToList();
lst.Add(line);
}
foreach (var item in lst)
{
for (int k = 0; k < item.Count; k++)
{
Console.WriteLine(item[k]);
}
}
}

Read text from a text file to a string multidimensional array

So I ran into a problem, I have a big text in a TXT file and I need to read it into a multidimensional array, without using LINQ.
Example:
Hello(a11) my(a12) friend(a13).
My(a21) name(a22) is(a23) David(a24),
I(a31) am(a32) from(a33) England(a34).
What I have done so far:
String input = File.ReadAllText( "..\\..\\Analize.txt" );
int i = 0, j = 0;
string[,] result = new string[10, 10];
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = string(col.Trim());
j++;
}
i++;
}
For the others who said his code "works just fine - true if his text is not dynamic size - but if there are more lines then 10, or more words then 10 in this particular example there will be an IndexOutOfRangeException !
If you do know anything about your file this is maybe the best for not running into exceptions:
string[] lines = File.ReadAllLines("C:/temp/test.txt");
int sizex = lines.Length;
int sizey = 1;
for (int i = 0; i < lines.Length; i++)
{
var splitline = lines[i].Split(' ');
sizey = sizey < splitline.Length ? splitline.Length : sizey;
}
String[,] multillines = new string[sizex,sizey];
for (int i = 0; i < lines.Length; i++)
{
var splitline = lines[i].Split(' ');
for (int j = 0; j < splitline.Length; j++)
{
multillines[i, j] = splitline[j];
}
}
Your code as it is works just fine. Not sure what your problem is. But if this:
Hello(a11)
means that this word has to sit on position [1,1] then all you have to change is the counting start from 0 to 1
int i = 1, j = 1;
Try this:
String input ="Hello(a11) my(a12) friend(a13)";
int i = 0, j = 0;
int[,] result = new int[10, 10];
foreach (var row in input.Split(' '))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = int.Parse(col.Trim());
j++;
}
i++;
}
Console.WriteLine(result[3,9]);

How to iterate over a multidimensional string array?

I have a 2d string array (at least I think it is called a 2d array):
var target = new string[var1,var2];
Now I want to convert it to List<List<string>>:
var listlist = new List<List<string>>();
foreach (var row in target)
{
var newlist = new List<string>();
foreach (var el in row)
{
newlist.Add(el);
}
listlist.Add(newlist);
}
But row has a type is string and el has type is char.
I can't understand why el is not a string? What's wrong?
A foreach interates over a string[,] like it is a string[]. It doesn't split in rows.
If you do want to handle 'rows' and 'columns' those separately, you have to get the dimensions of the array, using the GetLength method:
var target = new string[var1, var2];
var listlist = new List<List<string>>();
for (int x = 0; x < target.GetLength(0); x++)
{
var newlist = new List<string>();
for (int y = 0; y < target.GetLength(1); y++)
{
newlist.Add(target[x, y]);
}
listlist.Add(newlist);
}
This is what you need
static void SoStrList()
{
int var1=10, var2=7;
var target=new string[var1, var2];
var listlist=new List<List<string>>();
for(int i=0; i<var1; i++)
{
var row=new List<string>();
for(int j=0; j<var2; j++)
{
row.Add(target[i, j]);
}
listlist.Add(row);
}
}
use for loop instead of foreach
var target = new string[2, 2];
target[0, 0] = "a";
target[0, 1] = "A";
target[1, 0] = "b";
target[1, 1] = "B";
var listlist = new List<List<string>>();
for (int i = 0; i < target.GetLength(0); i++)
{
var newlist = new List<string>();
for (int j = 0; j < target.GetLength(1); j++)
newlist.Add(target[i,j]);
listlist.Add(newlist);
}
Here:
foreach (var row in target)
You already have first element of your 2d array, and foreach take all chars of this elements
well ... string is array of chars.
And this confusion is what you get from using keyword var for almost everything. Its not javascript.
Secondly : You need to go for something like this
for (int i = 0; i < target.GetLength(0); i++)
{
for (int y = 0; y < target.GetLength(1); y++)
{
your manipulation with strings
}
}
but srsly... get rid of vars !!!
For LINQ lovers, the same can be achieved using the following two lines:
int R = s.GetLength(0), C = s.GetLength(1);
var MyList = Enumerable.Range(0, R).Select(i => i * C).Select(i => s.Cast<string>.Skip(i).Take(C).ToList()).ToList();

How to convert List<string[]> to string[,]?

I converted a 2D array (string[,]) to the list below successfully. Now, how can I convert the List below back to a 2D array (string[,])?
List<string[]> NameList = new List<string[]>();
This is how I converted the 2D array to list:
List<string[]> NameList = new List<string[]>();
string[,] Name2DArray = new string[Rows.Count, 3];
for (int i = 0; i < Name2DArray.GetLength(0); i++)
{
string[] temp = new string[Name2DArray.GetLength(1)];
for (int n = 0; n < temp.Length; n++)
{
temp[n] = Name2DArray[i, n];
}
NameList.Add(temp);
}
Thanks all for your suggestions. I managed to fix the problem in my code. The conversion form List string[] to 2D array is now working. Below is the code:
string[,] newArray = new string[newTotalRows, 3];
for (int i = 0; i < NameList.Count; i++)
{
for (int j = 0; j < NameList[i].Length; j++)
{
newArray[i, j] = NameList[i][j];
}
}

How do I initialize a list of integer arrays in C#?

I need to create a list of integer arrays. I know ahead of time the length of the arrays, but I don't know how many of them need to be added to the list.
I've tried the following code:
List<int[]> MyListOfArrays = new List<int[]>();
int[] temp = new int[30];
range = xlApp.get_Range("NamedRange");
values = (object[,])range.Value2;
for (int i = 0; i < values.GetLength(0); i++)
{
for (int j = 0; j < values.GetLength(1); j++)
{
temp[j] = Convert.ToInt32(values[i + 1, j + 1]);
}
MyListOfArrays.Add(temp);
}
The temp array is filled just fine. However, MyListOfArrays just ends up with the last iteration of temp repeated for all of the entries. Where am I going wrong?
When you add the temp array to the List, it is just a pointer to the array created on the heap. You need to create a new temp array for every array you add to the list.
List<int[]> MyListOfArrays = new List<int[]>();
range = xlApp.get_Range("NamedRange");
values = (object[,])range.Value2;
for (int i = 0; i < values.GetLength(0); i++)
{
int[] temp = new int[30]; // moved inside the loop
for (int j = 0; j < values.GetLength(1); j++)
{
temp[j] = Convert.ToInt32(values[i + 1, j + 1]);
}
MyListOfArrays.Add(temp);
}
Here's the easiest fix.
Your code:
List<int[]> MyListOfArrays = new List<int[]>();
int[] temp = new int[30];// <-- Move this inside the 'i' for-loop.
range = xlApp.get_Range("NamedRange");
values = (object[,])range.Value2;
for (int i = 0; i < values.GetLength(0); i++)
{
for (int j = 0; j < values.GetLength(1); j++)
{
temp[j] = Convert.ToInt32(values[i + 1, j + 1]);
}
MyListOfArrays.Add(temp);
}
Do this instead:
List<int[]> MyListOfArrays = new List<int[]>();
range = xlApp.get_Range("NamedRange");
values = (object[,])range.Value2;
for (int i = 0; i < values.GetLength(0); i++)
{
int[] temp = new int[30]; //<-- This will create a new array of ints, with each iteration of 1.
for (int j = 0; j < values.GetLength(1); j++)
{
temp[j] = Convert.ToInt32(values[i + 1, j + 1]);
}
MyListOfArrays.Add(temp);
}
You just need to move the line:
int[] temp = new int[30];
immediately after:
for (int i = 0; i < values.GetLength(0); i++) {
so it initializes to a new array at each iteration of the loop.
MyListOfArrays.Add is adding the same reference to you list for each iteration of i, and it overwrites the values in temp[] each time. So you end up with the values of the last iteration repeated.

Categories

Resources