C# StreamReader 使用分隔符保存到数组
我有一个文本文件,其中包含制表符分隔的数据。我在 C# 应用程序中需要的是从文本文件中读取一行并将它们保存到一个数组中,在每个 \t
处将它们分开。然后我对下一行做同样的事情。
我的代码:
StreamReader sr = new StreamReader(dlg.FileName);
string s = sr.ReadLine();
现在,我已经尝试将该行写入数组,但这不起作用。有人知道如何管理这个吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
的数组
使用 Split 方法创建行 请参阅此处有关 Split() 的文档
Use the Split method to create an Array of the line
See Documentation on Split() here
s.Split('\t')
将按制表符拆分字符串,并创建一个具有适当长度的string[]
。s.Split('\t')
will split your string by the tabulator character, and create astring[]
with appropriate length.修改示例代码:
最后,items 包含一个字符串数组,表示选项卡之间的字符。选项卡不包含在数组中。该数组可能包含空元素(对于两个连续选项卡的情况)。
Ammending your example code:
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).
使用 String.Split() 方法:http:// /msdn.microsoft.com/en-us/library/b873y76a.aspx
Use the
String.Split()
method: http://msdn.microsoft.com/en-us/library/b873y76a.aspx如果你想保留新行的比
string[] content = reader.ReadToEnd().Split('\t');
if you want to keep New Line's than
string[] content = reader.ReadToEnd().Split('\t');
在下面的示例中,
items
将是一个包含每行文本值的String[]
。它将在每次迭代时被覆盖,因此您需要在循环内对其执行某些操作。将其保存到更大的集合中,将其写入文件等......In the example below,
items
will be aString[]
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...如果文件仅包含一行,则使用:
If the file contains only one line, then use: