Briknthewall
Briknthewall

Reputation: 149

StreamReader row and line delimiters

I am trying to figure out how to tokenize a StreamReader of a text file. I have been able to separate the lines, but now I am trying to figure out how to break down those lines by a tab delimiter as well. This is what I have so far.

string readContents;
using (StreamReader streamReader = new StreamReader(@"File.txt"))
{
    readContents = streamReader.ReadToEnd();
    string[] lines = readContents.Split('\r');
    foreach (string s in lines)
    {
        Console.WriteLine(s);
    }
}
Console.ReadLine();

Upvotes: 2

Views: 3823

Answers (2)

Antoine Pelletier
Antoine Pelletier

Reputation: 3316

string readContents;
using (StreamReader streamReader = new StreamReader(@"File.txt"))
{
    readContents = streamReader.ReadToEnd();
    string[] lines = readContents.Split('\r');
    foreach (string s in lines)
    {
         string[] lines2 = s.Split('\t');
         foreach (string s2 in lines2)
         {
             Console.WriteLine(s2);
         }
    }
}
Console.ReadLine();

not really sure if that is what you want, but... it breaks (tab) the already broken (return) lines

Upvotes: 2

Steve
Steve

Reputation: 633

Just call Split() on each of the lines and keep them in a List. If you need an array you can always call ToArray() on the list:

string readContents;
using (StreamReader streamReader = new StreamReader(@"File.txt"))
{
    readContents = streamReader.ReadToEnd();
    string[] lines = readContents.Split('\r');
    List<string> pieces = new List<string>();
    foreach (string s in lines)
    {
        pieces.AddRange(s.Split('\t'));
        Console.WriteLine(s);
    }
}
Console.ReadLine();

Upvotes: 2

Related Questions