I need to create an 2D array from a text file.
my text file looks like this
Name1:Id1:Class1:Status1
Name2:Id2:Class2:Status2
and so on
I want my multidimensional array to make something like this
array = {{name1,id1,class1,status1},{name2,id2,class2,status2}}
I have seen other post related to it but non seems to be helping thats why posting again
I assume that all of the lines have the same format. We can simply iterate through the lines as below:
string[] lines = File.ReadAllLines(filename);
int len0 = lines.Length;
int len1 = lines[0].Split(':').Length;
string[,] array = new string[len0, len1];
for (int i= 0; i < len0; i++)
{
string line = lines[i];
string[] fields = line.Split(':');
if (fields.Length != len1)
continue; // to prevent error for the lines that do not meet the formatting
for(int j = 0; j < len1; j++)
{
array[i,j] = fields[j];
}
}
Going to a jagged array is pretty easy. Going from a jagged array to a 2D array just requires some assumptions: like that all rows have the same number of items and that you know how many rows and columns there are when you create the array.
string.Split will help you create the jagged array. And a straightforward loop will help you create the multi-dimensional array.
using System;
using System.Linq;
class Program {
static void Main(string[] args) {
string input = #"Name1:Id1:Class1:Status1
Name2:Id2:Class2:Status2";
var jagged = input
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(s => s.Split(':').ToArray())
.ToArray();
var multi = new string[jagged.Length, jagged[0].Length];
for (int i = 0; i < jagged.Length; ++i) {
for (int j = 0; j < jagged[0].Length; ++j) {
multi[i, j] = jagged[i][j];
Console.WriteLine("[{0},{1}] = {2}", i, j, multi[i, j]);
}
}
}
}
It is better to use a List object like code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
List<List<string>> data = new List<List<string>>();
StreamReader reader = new StreamReader(FILENAME);
string line = "";
while ((line = reader.ReadLine()) != null)
{
List<string> lineArray = line.Split(new char[] { ':' }).ToList();
data.Add(lineArray);
}
reader.Close();
}
}
}
Related
An array of strings A is given. Each element consists of the clients surname and name. Create a row array B, consisting of substrings of elements of array A and
containing only clients names.
My code doesn't work.
I enter Donna Paulson, Jhon Elliot, and i get Donna, Elliot.
It needs to be Paulson, Elliot, because only names are needed
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clients
{
internal class Program
{
static void Main(string[] args)
{
int m = Convert.ToInt32(Console.ReadLine());
string[] A = new string[m];
string[] B = new string[m];
for (int i = 0; i < m; i++)
{
Console.Write($"A[{i}]= ");
A[i] = Console.ReadLine();
}
for (int i = 0; i < m; i++)
{
string[] text = A[i].Split(' ');
B[i] = text[i];
}
for (int i = 0; i < B.Length; i++)
{
Console.WriteLine(B[i]);
}
}
}
}
I have a problem with converting string array (previously loaded from .txt file) to integer one. File has got 100 random numbers, they load without any problem, I just need to convert them to integers to make them sortable with 3 types of sorting. I've tried many thing that were said here, but none of them seem to work. All the time I'm getting an error saying that it can't be converted.
Here is my loading from the file code:
string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
int[] numb= new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
And after some options to choose I'm using switch to pick one:
switch (a)
{
case 1:
Console.WriteLine("1. Bubble.");
//int[] tab = numb;
babel(path);
for (int z = 0; z < path.Length; z++)
{
Console.Write(path[z] + ", ");
}
break;
I've got bubble sorting method in my program too, don't think it is necessary to post it here.
If anyone can help me here, I'd be really grateful.
#Amy - I've tried this:
numb[i] = path[i].Convert.toInt32(); - it doesn't work.
What I want to achieve is to change every number in this array to int, I think it should be involved here:
{
Console.WriteLine(path[i]);
}
This conversion works.
#string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
String[] path = {"1","2","3"};
int[] numb = Array.ConvertAll(path,int.Parse);
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Length; i++)
{
Console.WriteLine(numb[i]);
}
It is better to use TryParse instead of parse. Also it is easier to work with List, than with array.
using System;
using System.Collections.Generic;
namespace StringToInt
{
class Program
{
static void Main(string[] args)
{
String[] path = { "1", "2", "3", "a", "b7" };
List<int> numb = new List<int>();
foreach (string p in path)
{
if (int.TryParse(p, out int result))
{
numb.Add(result);
}
}
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Count; i++)
{
Console.WriteLine(numb[i]);
}
}
}
}
I can't imagine this wouldn't work:
string[] path = File.ReadAllLines("C:\\Users\\M\\numb.txt");
int[] numb = new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
numb[i] = int.Parse(path[i]);
}
I think your issue is that you are using File.ReadLines, which reads each line into a single string. Strings have no such ToArray function.
I am trying to output a few numbers that are in the same line as a string by converting them from string to int im using split and trying to convert for first time and the output is system.int32[]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int Websites = int.Parse(Console.ReadLine());
int sectok = int.Parse(Console.ReadLine());
string[] webnamearray = new string[Websites];
int[] persums = new int[Websites];
int one = 0;
int two = 0;
string datainput = "";
for (int i = 0; i < Websites; i++)
{
datainput = Console.ReadLine();
string[] split = datainput.Split(' ');
webnamearray[i] = (split[0]);
one = int.Parse(split[1]);
two = int.Parse(split[2]);
persums[i] = one * two;
Console.WriteLine(persums);
}
for (int i = 0; i < Websites;i++)
{
Console.WriteLine(webnamearray[i]);
}
}
}
}
You wrote:
Console.WriteLine(persums);
which is an array of integers, that explains why you see that in your output.
I think instead your desired output is (which is your value that you just created):
Console.WriteLine(persums[i]);
and instead of if you want to place this information with the names change your last loop:
for (int i = 0; i < Websites;i++)
{
Console.WriteLine(webnamearray[i] + " " + persums[i]);
}
As much as I tried to find a similar version in the question here, I couldn't find something.. so I am asking your help.
After reading some numbers from a textfile (now in string format), I split them in rows and columns and add them to a 2d-array (in string format as well). Now I want to convert everythinh in integers so that I can play with sorting the numbers out later.
Here is my code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ArrayProgram
{
class Program
{
int number = 0;
int i = 0;
int k = 0;
string strnum;
public void onetohundredints()
{
StreamWriter writer = new StreamWriter("numberstored.txt");
for (i = 0; i < 10; i++)
{
for (k = 0; k < 10; k++)
{
number++;
Console.Write(number + " ");
strnum = number.ToString();
writer.Write(strnum + " ");
}
Console.WriteLine();
writer.WriteLine();
}
writer.Close();
}
public void readints()
{
StreamReader reader = new StreamReader("numberstored.txt");
string data = reader.ReadToEnd();
reader.Close();
string[,] dataarray = new string[10,10];
int[] numbers = new int[100];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
dataarray[i, j] = numbersperrow[j];
}
}
}
public static void Main(string[] args)
{
Program prog = new Program();
prog.onetohundredints();
prog.readints();
Console.ReadKey();
}
}
}
After I insert the number into the 2d-array, how do I convert all of it in integers?
If you don't have a particular reason to have an array of strings, you can just save you data as int in the first place. Just change your inner for loop to do:
var parsed = int.TryParse(numbersperrow[j], out dataarray[i, j]);
if (!parsed)
{
// Error
}
While that should work, I would suggest to re-write your ReadData method to look similar to the sample below.
public int[,] ReadData(string filePath, int xDimension, int yDimension)
{
var results = new int[xDimension, yDimension];
var lines = File.ReadLines(filePath);
for (var i = 0; i < allLines.Count(); i++)
{
var values = lines[i].Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
for (var j = 0; j < values.Count(); j++)
{
var parsed = int.TryParse(values[j], out results[i, j]);
if (!parsed) { }
}
}
return results;
}
You're putting everything into a string array. That array can only hold strings, not numbers. If you want to make the 2d array hold numbers, define it as int[,] dataarray = new int[10,10]; Next, in the final loop, simply do dataarray[i, j] = Convert.ToInt32(numbersperrow[j]);
Edit: You can use int.TryParse(numbersperrow[j], out value) if you aren't sure that numbersperrow[j] will be a number. Value will return false if the conversion is not successful.
I am happy to say that both solutions work. I now have my numbers in my 2d array. But now I wish to play with them. Let's say that I want the numbers printed on the screen in reverse order.
Having this correct solution:
int numbers;
int[,] dataarray = new int[10,10];
string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<=dataperlines.Count()-1; i++)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int j=0; j<=numbersperrow.Count()-1; j++)
{
numbers = int.Parse(numbersperrow[j]);
dataarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
I know that I have to make a double for loop. But how do I write a succesful syntax for the numbers to be printed properly?
I also tried this:
int[,] reversedarray = new int[10, 10];
reversedarray[i, j] = Array.Reverse(dataarray[i,j]);
but the dataarray[i,j] becomes red and the error "cannot convert from int to system.Array occurs... what am I missing?
I also tried this...
for (i = 10; i <= dataperlines.Count(); i--)
{
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (j =10; j <= numbersperrow.Count(); j--)
{
numbers = int.Parse(numbersperrow[j]);
reversedarray[i, j] = numbers;
Console.Write(numbers + " ");
}
Console.WriteLine();
}
But I have an IndexOutOfRange exception coming from
string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
I understood that since I splitted the columns into rows too, it is unecessary to write it again, but I am stuck. I tried simplifying the code since I have my 2darray with its elements and I my tries were fallacious. Any more suggestions?
Can you please help me with C#.
I am trying to create a function in C# that opens a CSV file and save them to an array:
FileStream fileStream = new FileStream(guid.ToString(), FileMode.Open);
for (int i = 1; i > 200; i++) // it checks the first 200 lines
{
int j = 0;
string[] str = new string[j];
do
{
// saving each character to the variable until comma is found
} while(str == '\n'); // read each character in a for loop until new line character found
}
Can you please help me out?
Something like this:
using (StreamReader r = new StreamReader(guid.ToString()))
{
string line;
int linesCount;
ArrayList result = new ArrayList();
while ((line = r.ReadLine()) != null && linesCount++ <= 200)
{
result.AddRange(line.Split(','));
}
}
Parsing CSV by hand is actually pretty tricky. You might be better off reusing the TextFieldParser (add a reference to the Microsoft.VisualBasic assembly).
using Microsoft.VisualBasic.FileIO;
....
string[,] parsedCsv;
List<string[]> csvLines = new List<string[]>();
TextFieldParser parser = new TextFieldParser(new FileStream(guid.ToString(), FileMode.Open));
parser.Delimiters = new string[] { "," };
parser.TextFieldType = FieldType.Delimited;
int maxLines = 200, lineCount = 0;
try
{
while (!parser.EndOfData && lineCount++ < maxLines)
{
csvLines.Add(parser.ReadFields());
}
}
catch (MalformedLineException)
{
Console.WriteLine("Line Number: {0} Value: {1}", parser.ErrorLineNumber, parser.ErrorLine);
return;
}
parsedCsv = new string[csvLines.Count, csvLines[0].Length];
for (int i = 0; i < csvLines.Count; i++)
{
for (int j = 0; j < csvLines[i].Length; j++)
{
parsedCsv[i, j] = csvLines[i][j];
}
}
I have assumed here that the output is going to be a 2-D array of strings - you may need to adjust this code depending on what you are after, especially if you have to cope with the situation where each line does not have the same number of fields (perhaps unlikely, but still).
The really useful thing about TextFieldParser is that it will cope with different kinds of delimeters. By setting parser.Delimiters = new string[] { "\t" };, for example, this same code could parse tab-delimited text.
What about:
string[] lines = File.ReadAllLines(path);
if(lines.Length >= 200){
for(int i = 0; i < 200; i++){
string[] str = lines[i].Split(',');
//do something here
}
}
You can just use the string.Split(',') extension method.
using (StreamReader streamReader = new StreamReader(File.OpenRead(guid.ToString())))
{
for (int i = 0; i <= 200; ++i)
{
string[] str = streamReader.ReadLine().Split(',');
}
}
The Split extension method will return a string array of the individual values separated by a comma.