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++;
}
Related
I have a multidimensional array that takes lines based on user input like(n lines/4col )
and I have a string of 4 numbers in a line separated by 1 space: 10.00 20.00 30.00 40.00. I need to assign each number to a column in 1 line. The code that I have until now:
int storeNumbers = int.Parse(Console.ReadLine());
string[,] storesemesterProfit = new string[storeNumbers, 4];
for(int m=0; m<storeNumbers; m++)
{
for(int n=0; n < 4; n++)
{
string inputData = Console.ReadLine()
string [] numb = inputData.Split(' ');
storesemesterProfit[m, n] = numb ; // i need help here
You might be looking for
int storeNumbers = int.Parse(Console.ReadLine());
var storesemesterProfit = new decimal[storeNumbers, 4];
for (var m = 0; m < storeNumbers; m++)
{
string inputData = Console.ReadLine();
var numb = inputData.Split(' ');
for (int n = 0; n < Math.Min(4, numb.Length); n++)
storesemesterProfit[m, n] = decimal.Parse(numb[n]);
}
Fair warning. This will likely explode if the user enters some bad data. I suggest taking a look at TryParse Methods
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);
}
}
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 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.
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]);
}