Read rows/columns of numbers in a text file (c#) - c#

I have a text file with the following numbers for example:
1 2 3
4 5 6
How do I read each individual number into an array?
It needs to move along each row so read in 1, 2 and then 3 into a array of then move to the second row and read 4 5 and 6.. and show the number of cells in a textbox.
this is my code, but I got an error.
List<string> list2 = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
char[] chars = lines[i].ToCharArray();
for (int j = 0; j < chars.Length; j++)
{
if (!Char.IsWhiteSpace(chars[j]))
list2.Add(chars[j].ToString());
}
}

You could convert it to a jagged int array:
int[][] result = text
.Split('\n')
.Select(line =>
line
.Split(' ')
.Select(numberText => int.Parse(numberText))
.ToArray()).ToArray();
Iterate through like this:
foreach (int[] line in result)
{
Console.WriteLine(string.Join(", ", line)); // or iterate through its numbers again
// or whatever you want to do
}
Edit
List<string> list2 = new List<string>();
string path = "xy"; //your path
string[] lines = File.ReadAllLines(path);
int[][] result = lines
.Select(line =>
line
.Split(' ')
.Select(numberText => int.Parse(numberText))
.ToArray()).ToArray();
foreach (int[] line in result)
{
list2.Add(string.Join(", ", line)); // or whatever format you want the text to be
}

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label3.Text = openFileDialog1.FileName;
textBox1.Text = File.ReadAllText(label3.Text);
FileStream fs = File.OpenRead(label3.Text);
string[] lines = new StreamReader(fs).ReadToEnd().Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
fs.Close();
List<string> list2 = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
char[] chars = lines[i].ToCharArray();
for (int j = 0; j < chars.Length; j++)
{
if (!Char.IsWhiteSpace(chars[j]))
list2.Add(chars[j].ToString());
}
}
}

Related

c# Splitting string to a multi dimensional array?

I encountered a little problem that i can't get my head around.
I have normal string[] array with a text import in it. Every row is stored in separate under every index.
A row usually look something like this:
string[i] = |title1|title2|title3|title4|title5|
string[i+1] = |Word1|Word2|Word3|Word4|Word5|
I want to split these rows and put them in a multi dimensional array.
Already counted how I have to declare the dimensions of the array.
I want to split it now. I was thinking about going through the normal array with two loops and look for the separator while saving the words in a string then copying it to the multi array.
Do you guys have any idea how could i do that, because this is too much hassle for such a small thing.
I want the multi array look something like this:
string[0,0] = title1,
string[0,1] = title2 etc.
string[1,0] = word1
string[1,1] = word2
This is the code that creates the array:
public string [,] SplitArrays(string [] arrayin)
{
long columns = 0;
char line = '|';
string row;
for(int i = 0; i < arrayin.Length;i++)
{
row = arrayin[i];
if (Convert.ToChar(row.Substring(0, 1)) == line)
{
for(int j = 0; j < row.Length;j++)
{
if (Convert.ToChar(row.Substring(j,(j+1))) == line)
{
columns++;
}
}
}
break;
}
int rowlength = arrayin.Length;
string[,] finalarray = new string[columns,rowlength];
And this is how far I got with separating, but I got kind of confuse and I probably messed it up:
int rowcolumncount = 0;
string word = "";
bool next = false;
for(int k = 0; k < arrayin.Length; k++)
{
row = arrayin[k];
for(int l = 0; l < row.Length; l++)
{
if (Convert.ToChar(row[l]) == line)
{
for(int z = 0; next == false;)
{
if(row[z] == line)
{
next = true;
}
else
{
string part = Convert.ToString(row[z]);
word = string.Join("",part);
}
finalarray[l, rowcolumncount] = word;
rowcolumncount++;
}
}
rowcolumncount = 0;
}
}
return finalarray;
}
The main array contains around 12000 lines.
Thank you!
You can try something like this: Split each item with arrayin by | and write these chunks into a line of 2D array:
public string[,] SplitArrays(string[] arrayin) {
if (null == arrayin)
return null;
else if (arrayin.Length <= 0)
return new string[0, 0];
// null : we don't know size (number of columns) before 1st line split
string[,] result = null;
int row = 0;
foreach (var line in arrayin) {
string[] items = line.Split('|');
// - 2 : skip the very first and the very last items which are empty
if (null == result)
result = new string[arrayin.Length, items.Length - 2];
// if line is too short, let's pad result with empty strings
for (int col = 0; col < result.GetLength(1); ++col)
result[row, col] = col + 1 < items.Length - 1
? items[col + 1]
: ""; // padding
row += 1;
}
return result;
}
Usage:
string[] source = new string[] {
"|title1|title2|title3|title4|title5|",
"|Word1|Word2|Word3|Word4|Word5|",
};
// {
// {"title1", "title2", "title3", "title4", "title5"},
// { "Word1", "Word2", "Word3", "Word4", "Word5"}
// }
string[,] array = SplitArrays(source);
If the number of items per line vary, you can use a jagged array.
We create the empty array and set the row count size.
Then we parse all lines of the list and for all line we split it to have desired items to add them into the dimension as we resize the row sub-array.
static public void Test()
{
var list = new string[]
{
"| title1 | title2 | title3 | title4 | title5 |",
"| Word1 | Word2 | Word3 | Word4 | Word5 |"
};
int indexD1 = 0;
string[][] result = null;
Array.Resize(ref result, list.Length);
foreach ( string item in list )
{
var str = item;
str = str.TrimStart('|').TrimStart();
str = str.TrimEnd('|').TrimEnd();
str = str.Replace(" | ", "|");
var items = str.Split('|');
Array.Resize(ref result[indexD1], items.Length);
int indexD2 = 0;
foreach ( string part in items )
result[indexD1][indexD2++] = part;
indexD1++;
}
foreach ( var row in result )
{
foreach ( var str in row )
Console.WriteLine(str);
Console.WriteLine();
}
}
You can also use a List of List of Strings and use the method Add():
var result = new List<List<string>>();

I want to replace the data in a text file with an array and store it in a variable

The goal is to graph the data in a text file.
I will store it as an int in the array y and as a string in the array x
There are two text files, x.txt and y.txt, each of which is separated by spaces. like y is 1 2 3 4 5 6 and x is a b c d.
I hope to store it in array, like
int[] y = {1, 2, 3, 4, 5, 6};
string[] x = {"a", "b", "c", "d"};
I try StreamReader... but I'm fail
so I want to give an example of my problem.
StreamReader sy = new StreamReader("F:/C#/graph/graph/bin/Debug/y.txt",
Encoding.Default);
string[] ty = sy.ReadToEnd().Split(' ');
Console.WriteLine(ty);
for (int i = 0; i < ty.Length; i++)
{
y[i] = Int32.Parse(ty[i]);
return;
}
You can try this solution:
using(System.IO.StreamReader sr = new System.IO.StreamReader("F:/C#/graph/graph/bin/Debug/x.txt"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] x = line.Split(' ');
}
}
using(System.IO.StreamReader sr = new System.IO.StreamReader("F:/C#/graph/graph/bin/Debug/y.txt"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] yString = line.Split(' ');
}
int[] y = Array.ConvertAll(yString , s => int.Parse(s));
}
It seems you leave the loop prematurely:
for (int i = 0; i < ty.Length; i++)
{
y[i] = Int32.Parse(ty[i]);
return; // <- Only 1st value will be read
}
When querying data (e.g. file) we often use Linq; StreamReader is an overshoot (put a simple File.ReadAllText) if you all we want is to read the entire file:
using System.Linq;
...
int[] y = File
.ReadAllText(#"F:/C#/graph/graph/bin/Debug/y.txt")
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item))
.ToArray();
string[] x = File
.ReadAllText(#"F:/C#/graph/graph/bin/Debug/x.txt")
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();

split String[] with seperators and convert it to 2D Array

There is is a problem in my c# code.
I have a string array with 23 values in each line, seperated by a semicolon.
I want to split each value and parse it into an 2D [double] Array that should look like:
[(number of lines),22].
The string array looks like:
[0]
0,00;111,00;0,00;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,10;-0,10;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00
[1]
0,00;120,00;0,00;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,10;-0,10;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00
The double array should look like:
[0,0] 0,00
[0,1] 111,00
[0,2] 0,00
[0,3] -1,00
and so on.
Do you have any ideas?
This is my current Code, that does not work.
double[,] values = new double[z, 22];
char[] seperator = { ';' };
int x = 0;
for (int i = 0; i < z; i++) {
for (int j = 0; j < 22; j++) {
values[i, j] = Data[x].Split(seperator);
x++;
}
}
How you could achieve this:
I use decimal here if you use double it will get the result 0 from a string like 0,00. So you can use double but if it can it will shorten it. Whit decimal a string like 0,00 will be 0.00
string[] arr = new string[] { "0,00;111,00;0,00;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,10;-0,10;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00" , "0,00;120,00;0,00;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,10;-0,10;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00" };
// array conaining decimals
decimal[,] numbers = new decimal[2,23];
// loop thrue strings in arr
for (int i = 0; i < arr.Length; i++)
{
// split that string by ';'
string[] numberStrings = arr[i].Split(';');
// loop thrue the result of the splitted strings
for (int j = 0; j < numberStrings.Length; j++)
{
// parse that number from splitted string to decimal an put it on his place in the 2d array
numbers[i, j] = decimal.Parse(numberStrings[j]);
}
}
Please, try this code.
String a1 = "0,00;111,00;0,00;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,00;0,10;-0,10;-1,00;-1,00;0,00;0,00;0,00;0,00;0,00";
// new array split string by ';'
String[] arr1 = a1.Split(';');
int count = 0;
Console.WriteLine("\n\n\n-----------\nType 1 (only 1 array) \n-----------\n\n\n");
while ( count <= arr1.Length -1){
Console.WriteLine(arr1[count].ToString());
count++;
}
Console.WriteLine("\n\n\n-----------\nType 2 (multidimensional array) \n-----------\n\n\n");
// new array split string by ';' and ','
String[] arr2 = a1.Split(';');
string[,] arrFinal = new string[23,2];
// re-start counter
count = 0;
while (count <= arr2.Length - 1)
{
arrFinal[count, 0] = arr2[count].ToString().Split(',')[0];
arrFinal[count, 1] = arr2[count].ToString().Split(',')[1];
Console.WriteLine(arr2[count].ToString());
Console.WriteLine("item ({0},{1}) = {2} | item ({3},{4}) = {5} ", count, "0", arrFinal[count, 0], count, "1", arrFinal[count, 1], arrFinal[count, 1] );
count++;
}

convert Text file 2D array to integer 2D array

I am trying to use data from text file (matrix [i, j]). I have code works with one dimension array but doesn't work with two dimension array. I tried to use different method but I always get an error.
string fileContent = File.ReadAllText(file path);
string[] integerStrings = fileContent.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
integers = new int[integerStrings.Length];
for (int n = 0; n < integerStrings.Length; n++)
integers[n] = int.Parse(integerStrings[n]);
I modify it to this
string fileContent = File.ReadAllText(path);
string[,] integerStrings = fileContent.Split(new char[,] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
integers = new int[integerStrings.Length,2];
for (int n = 0; n < integerStrings.Length; n++)
for (int j = 0; j <2; n++)
integers[n,j] = int.Parse(integerStrings[n,j]);
the text file
0 0
2 0
4 0
6 0
8 1
10 1
12 1
14 2
16 3
18 3
Note the code I need should be fixable with rows number
get the lines from the file then split each line to get your 2d array. Here is a rough first draft. You can test and refactor to improve on it if needed.
int[,] matrix = null;
int rowCount = 0;
int colCount = 0;
var lines = File.ReadAllLines(path);
rowCount = lines.Length;
for(int i = 0; i < rowCount; i++) {
var line = lines[i];
var tokens = line.Split(new []{' ', '\t'}, StringSplitOptions.RemoveEmptyEntries);
if(matrix == null) {
colCount = tokens.Length;
matrix = new int[rowCount, colCount];
}
for(int j = 0; j < colCount; j++) {
matrix[i, j] = int.Parse(tokens[j]);
}
}
this part is for display the matrix
int rowLength = matrix.GetLength(0);
int colLength = matrix.Rank;
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < colLength; j++) {
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.WriteLine();
Console.WriteLine();
}
Console.ReadLine();
If you want 2d array split method just gives 1d array so you have to split twice...
First split by line breaks then by spaces...
string[] rows = fileContent.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int[,] result = new int[rows.Length,2];
for(int i = 0; i < rows.Length; i++)
{
var col = rows[i].Split(new char{' ','\t'}, StringSplitOptions.RemoveEmptyEntries);
result[i,0] = int.Parse(col[0]);
result[i,1] = int.Parse(col[1]);
}

Create List of strings from the string inputted by the user c#

I have this method:
public List<string> AdvMultiKeySearch(string key)
{
string[] listKeys = key.Split(',');
string[] ORsplit;
List<string> joinedDashKeys = new List<string>();
List<string> joinedSearchKeys = new List<string>();
for (int i = 0; i < listKeys.Length; i++)
{
ORsplit = listKeys[i].Split('|');
joinedDashKeys.Add(string.Join(",", ORsplit));
}
for (int i = 0; i < joinedDashKeys.Count; i++)
{
string[] split = joinedDashKeys[i].Split(',');
for (int j = 0; j < split.Length; j++)
{
joinedSearchKeys.Add(string.Join(",", split[i]));
}
}
return joinedDashKeys;
}
I am trying to create a method that receives a string Keyword that is composed of the words,comas, and '|' character. For example, user enters
glu|sal,1368|1199
And method should produce/return List of strings: "glu,1368", "glu,1199", "sal,1368", "sal,1199"
It's been more than two hours and I still can't figure out how to correctly implement it. Can someone help please?
Given the input above this will show any number of combinations as long as there is one comma.
char[] splitter1 = new char[] { '|' };
char[] splitterComma = new char[] { ',' };
public List<string> AdvMultiKeySearch(string key)
{
List<string> strings = new List<string>();
string[] commaSplit = key.Split(splitterComma);
string[] leftSideSplit = commaSplit[0].Split(splitter1);
string[] rightSideSplit = commaSplit[1].Split(splitter1);
for (int l = 0; l < leftSideSplit.Length; l++)
{
for (int r = 0; r < rightSideSplit.Length; r++)
{
strings.Add(leftSideSplit[l] + "," + rightSideSplit[r]);
}
}
return strings;
}

Categories