I need to assign string to array columns after split method c# - c#

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

Related

How to refactor this code to combine several sections?

Let's say I have these 3 not so different codes.
How can I combine them, or let's just say I want to enter 10 numbers once I open the application.
I want those numbers to be added to each other, and at the same time show me if the number is even or not.
Here is the input code:
int[] dizi = new int[10];
for (int i=0; i<=10; i++)
{
dizi[i] = Convert.ToInt32(Console.ReadLine());
}
Here is the addition code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
toplam=toplam+sayi;
}
Console.WriteLine("Dizideki sayıların toplamı = " + toplam);
Here is the even number code:
int[] dizi[i]
int toplam=0;
foreach(int sayi in dizi)
{
if (sayi%2 ==0)
Console.WriteLine(sayi);
}
All code in one for loop.
For input 10 elements you need for from 0 to i < array.Length
because array int[10] access by index from 0 to 9
var array = new int[10];
var sum = 0;
for (var i = 0; i < array.Length; i++)
{
var number = Convert.ToInt32(Console.ReadLine());
sum += number;
if (number % 2 == 0)
Console.WriteLine($"The number {number} is even");
}
Console.WriteLine($"Sum = {sum}");

Is there a way to read an exact amount of split integers in C#?

Basically I've got this code:
var inputData = Console.ReadLine().Split(' ');
int N = int.Parse(inputData[0]);
int K = int.Parse(inputData[1]);
int[] A = new int[N];
From the console I need to read N and K like this:
4 2
In order to input elements in the array 'A', I need to read elements like this:
45 50 47 46
I figured out how to read N and K , but to fill the array , if N is let's say 35 , I must read exactly 35 numbers from a single line , how do I do that?
I've tried Fabio's solution and the code turned out like this:
var inputData = Console.ReadLine().Split(' ');
int N = int.Parse(inputData[0]);
int K = int.Parse(inputData[1]);
int[] A = new int[N];
var elements = Console.ReadLine().Split(' ').Take(N).ToArray();
for (int i = 0; i < N; i++)
{
A[i] = Convert.ToInt32(elements[i]);
}
That worked perfectly!
P.S
I am still trying to grasp StackOverflow's rules for asking question and formatting my questions so I'm sorry for leaving this huge chunk here and I want to thank everybody for reaching out.
Sounds like you'll read the first line, to get the size of the array, then read another line. You didn't say what you do with K.. maybe it's the number of lines of N elements..
var inputData = Console.ReadLine().Split();
int N = int.Parse(inputData[0]);
int K = int.Parse(inputData[1]);
var inputs = new List<int[]>();
for(k = 0; k < K; k++){
Console.Write($"Enter {N} numbers separated by spaces: ");
inputData = Console.ReadLine();
var bits = inputData.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
if(bits.Length == N)
inputs.Add(bits); //they did put N entries, woot
else
k--; //make them do it again
}
If the inputs are all on a single line (e.g., N, then K, then all the array values), you can do this:
var inputData = Console.ReadLine().Split(' ');
int N = int.Parse(inputData[0]);
int K = int.Parse(inputData[1]);
int[] A = inputData.Skip(2).Take(N).Select(int.Parse).ToArray();
If the values for the array A are on a separate line, you can do this:
var inputData = Console.ReadLine().Split(' ', 2);
int N = int.Parse(inputData[0]);
int K = int.Parse(inputData[1]);
int[] A = Console.ReadLine().Split(' ', N).Select(int.Parse).ToArray();

How to make a Jagged Array?

Thinking like a simple array:
Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());
string[] strA = new string[x];
strA[0] = "Hello";
strA[1] = "World";
for(int i = 0;i < x;i++)
{
Console.WriteLine(strA[i]);
}
Now, how can I do it with a double array?
I've already tried this:
Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());
// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y];
strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys";
for(int i = 0;i < x;i++)
{
for(int j = 0;i < y;i++)
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}
}
If's there's a simpler way of doing this, i'll be happy to learn it.
It's only for knowledge, I'm studying double array for the first time, so have patience please :)
Here's my example:
https://dotnetfiddle.net/PQblXH
You are working with jagged array (i.e. array of array string[][]), not 2D one (which is string[,])
If you want to hardcode:
string[][] strA = new string[][] { // array of array
new string[] {"Hello", "World"}, // 1st line
new string[] {"Thanks", "Guys"}, // 2nd line
};
in case you want to provide x and y:
string[][] strA = Enumerable
.Range(0, y) // y lines
.Select(line => new string[x]) // each line - array of x items
.ToArray();
Finally, if we want to initialize strA without Linq but good all for loop (unlike 2d array, jagged array can contain inner arrays of different lengths):
// strA is array of size "y" os string arrays (i.e. we have "y" lines)
string[][] strA = new string[y][];
// each array within strA
for (int i = 0; i < y; ++i)
strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)
Edit: Let's print out jagged array line after line:
Good old for loops
for (int i = 0; i < strA.Length; ++i) {
Console.WriteLine();
// please, note that each line can have its own length
string[] line = strA[i];
for (int j = 0; j < line.Length; ++j) {
Console.Write(line[j]); // or strA[i][j]
Console.Write(' '); // delimiter, let it be space
}
}
Compact code:
Console.Write(string.Join(Environment.newLine, strA
.Select(line => string.Join(" ", line))));
You're using a jagged array instead of a multidimensional one. Simply use [,] instead of [][]. You can then use it with new string[x, y].
First you need to clarify thing in your head before writing code.
I will recommend writing in simple phrase what you want to do. The code in your fiddle go into every direction. I will address the code in the fiddle and not your questionas you have typo error and other issue that where not present in the fiddle while the fiddle has error that the question do not have.
To simplify the problem lets use clear understandable names. The 2d array will be an table, with rows and columns.
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns:");
var y = int.Parse(Console.ReadLine());
var table = new string[x, y];
You need to to declare your table before knowing its size.
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row, col] = Console.ReadLine();
}
}
table.GetLength(0) is equivalent to X, and table.GetLength(1) is equivalent to Y, and can be replace.
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.Write(table[row, col]);
}
Console.Write("\n");
}
For a 3x3 table with 00X, 0X0, X00 as inputs the result is
00X
0X0
X00
It works. You separate each cell when we display by simply adding a comma or a space.
Fiddle
And for Jagged Array:
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
var table = new string[x][];
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
Console.WriteLine($"Enter of the line n°{row}");
var lineSize = int.Parse(Console.ReadLine());
table[row] = new string[lineSize];
for (int col = 0; col < table[row].Length; col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row][col] = Console.ReadLine();
}
Console.Write("\n");
}
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.Length; row++)
{
for (int col = 0; col < table[row].Length; col++)
{
Console.Write(table[row][col]);
}
Console.Write("\n");
}
Wrong variable in use:
for(int j = 0;i < y;i++) <- Should be j
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}

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

C# foreach loop take values from outer loop to inner loop

I have the below code.
int[] a = new int[] { 8, 9 };
for(int i=0;i<n;i++)
{
print i;
int z;
//during first iteration
z=8;
during second iteration
z=9;
}
Output should be something like this.
during first iteration i=0 and z=8
during second iteration i=1 and z=9
array a contains 2 elements. N and number of elements in array a will be always same. next my for loop will execute. during first iteration want z value should be 8(first element of array ) and second iteration my z value should be 9. I want to map 1st element of integer array to first iteration of for loop and so on.
try
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
int z = a[i]; // this line will get value from a one by one, 0, 1, 2, 3 and so on...
}
Edit 1 -
After seeing the comments on the other answer, the array 'a' turns out is a dynamic array which have size n (which is 2)
the revised edition:
int n = 2;
int[] a = new int[n];
string input = null;
for (int i = 0; i < a.Length; i++) // or i < n if you want
{
print i;
input = Console.ReadLine();
try {
a[i] = int.Parse(input);
Console.WriteLine(string.Format(
"You have inputted {0} for the {1} element",
input, i
));
} catch { Console.WriteLine("Non integer input"); i -= 1; }
}
you can try this
int [] a = {8,9};
for(int i=0; i< a.Length; i++)
{
int z = a[i]; //for taking value from array at the specific ith position
Console.WriteLine("i: " + i + " z:" + z);
}
try this
List<int> a = new List<int>();
int n = 2; // you can change it according to your need
for (int i = 0; i < n; i++)
{
string str = Console.ReadLine(); // make sure you enter an integer and conver it
int z = int.Parse(str);
a.Add(z);
}
foreach (int k in a)
{
Console.WriteLine(k);
}

Categories