【问题标题】:StreamReader row and line delimitersStreamReader 行和行分隔符
【发布时间】:2015-05-12 19:56:37
【问题描述】:

我试图弄清楚如何标记文本文件的 StreamReader。我已经能够将这些行分开,但现在我正试图弄清楚如何通过制表符分隔符来分解这些行。这是我目前所拥有的。

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

【问题讨论】:

  • 我不明白。如果每一行都有由制表符分隔的列,那么在回车符处拆分行的相同方法可以在制表符处拆分一行并从您的行中呈现字符串数组
  • 如果要按换行符分割,为什么要调用ReadToEnd()?调用 ReadLine() 将读取一行,您可以通过制表符或其他方式进行迭代或拆分。
  • @DourHighArch 这是一个很好的观点。我记得以前遇到过一个问题,然后直接跳到这个解决方案。我可能很快就会切换回那个。

标签: c# arrays tokenize delimiter streamreader


【解决方案1】:
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();

不确定这是否是您想要的,但是...它会破坏(制表符)已经破坏(返回)的行

【讨论】:

    【解决方案2】:

    只需在每一行上调用Split() 并将它们保存在一个列表中。如果您需要一个数组,您可以随时在列表中调用ToArray()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-04-28
      相关资源
      最近更新 更多