C# StreamReader save to Array with separator

て烟熏妆下的殇ゞ 提交于 2019-12-20 07:19:13

问题


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');


来源:https://stackoverflow.com/questions/8714197/c-sharp-streamreader-save-to-array-with-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!