C# StreamReader save to Array with separator

2019-03-04 18:15发布

问题:

I´ve got a text file with tabulator separated data. What I need in my C# application is that I read one line from the text file and save them to an array, separate them at the each \t. Then I do the same thing with the next row.

My code:

StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();

Now, I already tried to write the line into an array but that doesn´t work. Does anyone one how to manage this?

回答1:

Use the Split method to create an Array of the line

string[] parts = s.Split('\t');

See Documentation on Split() here



回答2:

    foreach (string line in System.IO.File.ReadAllLines(dlg.FileName))
    {
        var myArray = line.Split('\t');
    }


回答3:

s.Split('\t') will split your string by the tabulator character, and create a string[] with appropriate length.



回答4:

Ammending your example code:

StreamReader sr = new StreamReader(dlg.FileName); 
string s = sr.ReadLine(); 
var items = s.Split('\t'); 

In the end, items contains an array of strings that represent the characters between the tabs. The tabs are not included in the array. The array may contain empty elements (for the case of two consecutive tabs).



回答5:

Use the String.Split() method: http://msdn.microsoft.com/en-us/library/b873y76a.aspx



回答6:

StreamReader reader = new StreamReader("input.txt");
string[] content = reader.ReadToEnd().Replace("\n","").Split('\t');

if you want to keep New Line's than

string[] content = reader.ReadToEnd().Split('\t');



回答7:

In the example below, items will be a String[] containing each line of text's values. It will be overwritten with each iteration so you'll want to do something with it inside the loop. Save it to a larger collection, write it to a file, etc...

StreamReader sr = new StreamReader(dlg.FileName);
while (sr.Peek() >= 0) {
    var line = sr.ReadLine();
    var items = line.Split(new Char[] { '\t' });
}


回答8:

If the file contains only one line, then use:

string[] myArray = s.Split('\t');