我在这里要做的是从txt文件中删除最长的行。代码完成它的工作,但我也需要删除多个“最长行”和空白行。关于如何做的任何想法?
代码在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++;
}
}
}
}
}
答案 0 :(得分:0)
我建议使用LINQ。利用.Max扩展方法并迭代字符串数组。
string[] lines = { "1", "two", "three" };
var longestLine = lines.Max(line => line.Length);
var revised = lines.Where(line => line.Length < longestLine).ToArray();
修订后的变量将包含一个字符串数组,该数组排除行数最长的行。
答案 1 :(得分:0)
读取行,过滤掉空行和10条最长行,写入行:
string[] lines = File.ReadAllLines(inputFile, Encoding.GetEncoding(1257));
var filtered = lines
.Where(line => line.Length > 0) // remove all empty lines
.Except(lines.OrderByDescending(line => line.Length).Take(10)); // remove 10 longest lines
File.WriteAllLines(outputFile, filtered);
答案 2 :(得分:-1)
您可以识别最长的行,然后遍历列表,删除所有长度。要删除空的,你可以测试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);
}
}