0
string candidates;
string[] candidatesSplit = { };
string line;
int countLines = 0;

StreamReader sr = new StreamReader("..\\..\\..\\candidates.txt"); // Read candidates from file

candidates = sr.ReadToEnd();
sr.Close();

candidatesSplit = candidates.Split(','); // Split the file with ','

Console.WriteLine(candidatesSplit[30]);

Using this code, I wanted to split every ',' and get specific words out from my text file.

My candidates file looks like this:

100,Esra Tarak,90,D1,D4,D2,A,B,D,C, ,C,A,D,B,C,D,B,A, ,B,A,C,D,C,D,A,D,B,C,D
101,Cem Ak,84,D1,D5, ,A,C,D,C,C,C,A,C,B,C,D,B,A,C,B,A,C,D,C,C,A,D,B,C,D

Code works perfectly for the first line in candidates.txt, however when it comes to the second line on the text file, the output comes out like this:

D
101

I need it to show only like this

101

I cannot put a ',' at the end of my lines. Is there any way to fix this?

1 Answers1

1

Just Split(Environment.NewLine) on the entire input first and then Split(',') again on each line.

using var sr = new StreamReader("..\\..\\..\\candidates.txt");
var candidates = sr.ReadToEnd();

foreach (var line in candidates.Split(Environment.NewLine))
{
    var candidatesSplit = line.Split(',');
    Console.WriteLine(candidatesSplit[30]);
}
Good Night Nerd Pride
  • 8,245
  • 4
  • 49
  • 65