繁体   English   中英

如何使用C#读取和过滤文本文件中的行

[英]How to read and filter lines in text file Using C#

1)我有一个像这样的文本文件。

 Dilantha code 65 po Bo 1255 colombo sri lanka joy code 78 toronto Canada 

2)但我想要以下结果。 (我不希望代码65代码78部分)

 Dilantha colombo sri lanka joy toronto Canada 

3)我的要求是,首先我想读取文本文件,然后我想过滤上面2中显示的结果。

这是我的代码。 我正在使用C#

    String line;
    String path = "c:/sample.txt";

    StreamReader sr = new StreamReader(path);
    while ((line = sr.ReadLine()) != null)
    {
        //display the readed lines in the text box
        disTextBox.AppendText(line+Environment.NewLine);
    }

使用StringBuilder连接您读入的行
使用正则表达式跳过“代码xx”行
遇到新行时,打印出StringBuilder中的内容
完成文件后,如果StringBuilder中还有任何内容,请将其打印出来

static Regex codeRegex = new Regex("^code [\\d]+", RegexOptions.Compiled);

    static void Main(string[] args)
    {
        String line;
        String path = "c:/sample.txt";
        StringBuilder sb = new StringBuilder();

        StreamReader sr = new StreamReader(path);
        while ((line = sr.ReadLine()) != null)
        {
            line = line.Trim();

            if (codeRegex.IsMatch(line))
                continue;

            if (string.IsNullOrEmpty(line))
            {
                System.Console.Write(sb.ToString().Trim() + Environment.NewLine);
                sb.Clear();
            }
            else
            {
                sb.Append(line);
                sb.Append("\t");
            }
        }

        if (!string.IsNullOrEmpty(sb.ToString().Trim()))
            System.Console.Write(sb.ToString().Trim() + Environment.NewLine);
    }

如何创建一个函数来返回一个组的字符串列表,然后可能是一个类来保存值?

public static List<string> ReadGroup(TextReader tr)
{
    string line = tr.ReadLine();
    List<string> lines = new List<string>();
    while (line != null && line.Length > 0)
    {
        lines.Add(line);
    }

    // change this to line == null if you have groups with no lines
    if (lines.Count == 0) 
    {
        return null;
    }

    return lines;
}

然后,您可以按列表中的索引访问行:

String line;
String path = "c:/sample.txt";

using (StreamReader sr = new StreamReader(path))
{
    while ((List<string> lines = ReadGroup(sr)) != null)
    {
        // you might want to check for lines.Count >= 4 if you will
        // have groups with fewer lines to provide a better error

        //display the readed lines in the text box
        disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}",
            lines[0], lines[2], lines[3], Environment.NewLine);
    }
    sr.Close();
}

我注意到你的第一个有一个“po Bo 1255”的额外线。 您需要知道您的文件的格式是什么有意义。 如果组的最后两行是城市和国家/地区,则需要使用行数。 上课:

class LineGroup // name whatever the data contains
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string City { get; set; }
    public string Country { get; set; }

    public LineGroup(List<string> lines)
    {
        if (lines == null || lines.Count < 4)
        {
            throw new ApplicationException("LineGroup file format error: Each group must have at least 4 lines");
        }

        Name = lines[0];
        Code = lines[1];
        City = lines[lines.Count - 2];
        Country = lines[lines.Count - 1];
    }
}

并处理:

while ((List<string> lines = ReadGroup(sr) != null)
{
    LineGroup group = new LineGroup(lines);

    //display the readed lines in the text box
    disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}",
        group.Name, group.City, group.Country, Environment.NewLine);
}

也许你可以从这个(或其他)开始:

foreach (var line in File.ReadLines(myFilePath)) {
  if (line.Equals("code 65") || line.Equals("code 78")) 
    continue;

  // some logic to format lines into columns....
  // ....Append(string.Format("{0, -15}{1, -15}{2, -15}", lineValue1, lineValue2, lineValue3));
}

仅适用于.NET 4.0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM