删除txt中最长的行 [英] Deleting longest line from txt

查看:105
本文介绍了删除txt中最长的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里想要做的是从txt文件中删除最长的行.代码可以做到这一点,但是我也需要它来删除多条最长的行"和空白行.有关如何执行操作的任何想法?

what i'm trying to do here is to delete the longest line from a txt file. Code does it's job, but i also need it to delete multiple "longest lines" and blank lines as well. Any ideas on how to do it?

代码在C#中

    namespace _5_2
    {
    //------------------------------------------------------------
    class Program
    {
         const string CFd = "..\\..\\U1.txt";
         const string CFr = "..\\..\\Results.txt";
         static void Main(string[] args)
         {
             int nr;
             Read(CFd, out nr);
             Print(CFd, CFr, nr);
             Console.WriteLine("Longest line nr. {0, 4:d}", nr + 1);
             Console.WriteLine("Program done");
         }
         //------------------------------------------------------------
         /** Finds number of the longest line.
         @param fv - text file name
         @param nr - number of the longest line */
         //------------------------------------------------------------
         static void Read(string fv, out int nr)
         {
             string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
             int ilgis = 0;
             nr = 0;
             int nreil = 0;
         foreach (string line in lines)
         {
            if (line.Length > ilgis)
               {
                  ilgis = line.Length;
                   nr = nreil;
               }
              nreil++;
          }
        }
         static void Print(string fv, string fvr, int nr)
         {
             string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
             int nreil = 0;
             using (var fr = File.CreateText(fvr))
             {
                 foreach (string line in lines)
                 {
                     if (nr != nreil)
                     {
                         fr.WriteLine(line);
                     }
                     nreil++;
                 }
             }
         }
      }
  }

推荐答案

您可以确定最长的行,然后遍历列表,删除所有长度.要也删除空的,可以对String.IsNullOrWhiteSpace进行测试.

You could identify the longest line, and then loop through the list, deleting all of that length. To also delete empty ones, you could test against String.IsNullOrWhiteSpace.

(伪代码)之类的东西

     foreach (string line in lines)
     {
        if (String.IsNullOrWhiteSpace(line)) 
        {
            lines.Delete(line);
            Continue;
        }
        if (line.Length >= longestLine) // ">=" instead of "==" just to be on the safe side
        {
           lines.Delete(line);
        }
    }

这篇关于删除txt中最长的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆