C#: Read a text file into a 2D char array - c#

Like I mentioned above, I try to read a text file into a 2D char array.
That's my file:
abcde
fghij
klmno
pqrst
uvwxy
and that's my code:
var path = #"C:text.file";
StreamReader sr = File.OpenText(path);
{
char[,] arr = new char[5, 5];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
arr[i, j] = (Char)sr.Read();
Console.WriteLine(arr[i, j] + " = {0},{1}", i,j);
}
}
Console.WriteLine(arr[2,1]);
}
}
and at least my output:
1 = 0,0
2 = 0,1
3 = 0,2
4 = 0,3
5 = 0,4
= 1,0
= 1,1
6 = 1,2
7 = 1,3
8 = 1,4
9 = 2,0
0 = 2,1
= 2,2
...
so my question is, why e.g. arr[1,0] or arr[1,1] is empty?
thanks for your help!
sno0z3

The problem is caused by the presence of a newline at the end of each line (and a newline is composed of two characters in a Windows text file).
So you can check for these characters before adding to your array, or simply read the line (thus removing the newline) and then loop over the string obtained extracting char by char and adding them to your array
char[,] arr = new char[5, 5];
for (int i = 0; i < 5; i++)
{
string curLine = sr.ReadLine();
for (int j = 0; j < curLine.Length; j++)
{
arr[i, j] = curLine[j];
Console.WriteLine(arr[i, j] + " = {0},{1}", i,j);
}
}

Related

How do I print # in a nested for loop [duplicate]

This question already has an answer here:
What is an "index out of range" exception, and how do I fix it? [duplicate]
(1 answer)
Closed 4 years ago.
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[6];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
Hi guys. I need to print # one and then # twice, until i get to six times. It says System.index.out.of.range. How come?
You should try to extend your array, it's limited to 6 elements but you try to access 7 elements as you go through 0 to 6.
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[7];
doors[i] = "#";
for (int j = 1; j <=i; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
If
I need to print # one and then # twice, until i get to six times.
You don't want any array - string[] doors = new string[6];, just loops:
for (int line = 1; line <= 6; ++line) {
for (int column = 1; column <= line; ++column) {
Console.Write('#');
}
Console.WriteLine();
}
If you have to work with array (i.e. array will be used somewhere else), get rid of magic numbers:
// Create and fill the array
string[] doors = new string[6];
for (int i = 0; i < doors.Length; i++)
doors[i] = "#";
// Printing out the array in the desired view
for (int i = 0; i < doors.Length; i++) {
for (int j = 0; j < i; j++) {
Console.Write(doors[j]);
}
Console.Writeline();
}
Please, notice that arrays are zero-based (array with 6 items has 0..5 indexes for them)
because it is out of range.
change it to this:
for (int i = 0; i <= 6; i++)
{
string[] doors = new string[6];
doors[i] = "#";
for (int j = 0; j <=i.length; j++)
{
Console.Write(doors[j]);
}
Console.Writeline():
}
No need to use 2 loops. Just repeat that character
for (int i = 0; i <= 6; i++)
{
Console.Write(new String("#",i));
Console.WriteLine():
}

Convert string from text file to integer array

I wrote this code in order to open a text file in a C# language
Each line in the file contains five digits such as
0 0 2 3 6
0 1 4 4 7
0 2 6 9 9
1 0 8 11 9
1 1 12 15 11
2 2 12 17 15
The distance between the number and the other is one tab
The problem is when you execute the program this error appears
input string was not in correct format in Convert.ToInt32(t[j])
code:
string[] st = File.ReadAllLines("C:\\testing\\result.txt");
int[,] tmp = new int[st.Length - 1, 5];
for (int i = 1; i < st.Length; i++)
{
string[] t = st[i].Split(new char[] { ' ' });
int cnt = 0;
for (int k = 0; k < t.Length; k++)
if (t[k] != "")
{ t[cnt] = t[k]; cnt++; }
for (int j = 0; j < 5; j++)
tmp[i - 1, j] = Convert.ToInt32(t[j]);
}
How can i correct that?
I suggest changing the collection type from 2d array int[,] into jagged one int[][] and then use Linq:
using System.Linq;
...
int[][] data = File
.ReadLines(#"C:\testing\result.txt")
.Select(line => line
// Uncomment this if you have empty lines to filter out:
// .Where(line => !string.IsNullOrWhiteSpace(line))
.Split(new char[] {'\t'}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item))
.ToArray())
.ToArray();
split char should be a tab character '\t' instead of single space
You have five numbers per row, but not necessarily five digits. You will need a more complex solution, like this:
string[] st = File.ReadAllLines("C:\\testing\\result.txt");
int[,] tmp = new int[st.Length - 1, 5];
bool isAlreadyNumber = false;
bool isEmptyRow = true;
int rowIndex = -1;
int colIndex = -1;
for (int i = 0; i < st.Length; i++) {
isAlreadyNumber = false;
isEmptyRow = true;
foreach (char c in st[i]) {
if ((c >= '0') && (c <= '9')) {
if (isAlreadyNumber) {
tmp[rowIndex][colIndex] = tmp[rowIndex][colIndex] * 10 + (c - '0');
} else {
tmp[rowIndex][colIndex] = c - '0';
if (isEmptyRow) rowIndex++;
isEmptyRow = false;
isAlreadyNumber = true;
}
} else {
isAlreadyNumber = false;
}
}
}
Note, that the indexing was fixed. This untested code handles other separators and empty lines as well, but still assumes there will be five numbers.

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]);
}

Saving Text to array

I have been using this link as an example, but have been having troubles with it:
2d Array from text file c#
I have a textfile that contains :
1 1 0 0
1 1 1 0
0 0 0 1
0 1 0 0
And I'm trying to use the function:
static void Training_Pattern_Coords()
{
String input = File.ReadAllText(#"C:\Left.txt");
int i = 0, j = 0;
int[,] result = new int[4, 4];
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(' '))
{
result[i, j] = int.Parse(col.Trim());
j++;
}
i++;
}
Console.WriteLine(result[1, 3]);
Console.ReadLine();
}
However I keep getting the error message (Input String was not in correct format) at the line :
foreach (var row in input.Split('\n'))
I think it has something to do with the spaces within the textfile but I'm not entirely sure. Thanks for your help!
Instead of File.ReadAllText use File.ReadLines.By doing that you won't need to use Split('\n').
int[,] result = new int[4, 4];
var lines = File.ReadLines(#"C:\Left.txt")
.Select(x => x.Split()).ToList();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i, j] = int.Parse(lines[i][j]);
}
}
Try ReadAllLines as opposed to ReadAllText
Replace any \r (carriage return)
input = input.Replace('\r',' ');
Replace your \r to "\r\n"
Try this:
foreach (var row in input.Split("\r\n"))

Categories