thecner thecner -4 years ago 101
C# Question

How to cut multiple strings from txt filec#

I tried a lot of possible solutions to this problem but it never seems to work. My problem is the following: I have a txt file with several lines. Each line has something like:

xxxxx yyyyyy
xxxxx yyyyyy
xxxxx yyyyyy
xxxxx yyyyyy
...


I want to store in one array of strings the
xxxxx
and in another array the
yyyyy
, for each line on the txt file, something like

string[] x;
string[] y;

string[1] x = xxxxx; // the x from the first line of the txt
string[2] x = xxxxx; // the x from the second line of the txt
string[3] x = xxxxx; // the x from the third line of the txt


...

and the same for
string[] y
;

... but i have no idea how to...

I would very much appreciate if someone showed me how to make the cycle for this problem i have.

Answer Source

You can use linq for this:

string test = "xxxxx yyyyyy xxxxx yyyyyy xxxxx yyyyyy xxxxx yyyyyy";
string[] testarray = test.Split(' ');
string[] arrayx= testarray.Where((c, i) => i % 2 == 0).ToArray<string>();
string[] arrayy = testarray.Where((c, i) => i % 2 != 0).ToArray<string>();

Basically,this code splits the string by a space, and then puts the even strings in one array and the odd ones in another.

Edit

You say in the comments you don't understand this: Where((c, i) => i % 2 == 0). What it does is taking the position of each string (i) and does a mod of it with 2. This means, it divides the position by 2 and checks if the remain equals 0. It is the way to get if a number is odd or even.

Edit2

My first answer only works for one line. For several ones(as your input source is a file with several lines), you'll need to do a foreach loop. Or you can do something like the next sample code: read all the lines, join them in a single string, and then run the prevously showed code on the result:

string[] file=File.ReadAllLines(@"yourfile.txt");
string allLines=file.Aggregate((i, j) => i + " " + j); //this joins all the lines into one
string[] testarray = allLines.Split(' ');
string[] arrayx= testarray.Where((c, i) => i % 2 == 0).ToArray<string>();
string[] arrayy = testarray.Where((c, i) => i % 2 != 0).ToArray<string>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download