我需要找到这两个文本文件的哪一行是我最长的文本片段。我找到了,但我不知道如何在哪一行中找到我的文本片段。也许我需要以某种方式改变我的ReadFile方法?
string[] Fragment(string[] wordsWithSeparatos1, string[] wordsWithSeparators2)
{
int place = 0;
string[] fragment = new string[1000];
for (int i = 0; i < wordsWithSeparatos1.Length; i++)
{
for (int j = 0; j < wordsWithSeparators2.Length; j++)
{
if (wordsWithSeparatos1[i] == wordsWithSeparators2[j])
{
fragment[place] += wordsWithSeparatos1[i] + ' ' ;
i++;
}
else
{
if (fragment[place] != null)
{
place++;
}
}
}
}
return fragment;
}
void LongestFragment(string[] fragment)
{
foreach (var item in fragment.OrderByDescending(x => fragment.Length).Take(1))
{
Console.WriteLine(item);
}
}
string[] ReadFile(string fn)
{
char[] space = { ' ' };
string lines = File.ReadAllText(fn, Encoding.GetEncoding(1257));
string[] wordsWithSeparators = new string[1000];
wordsWithSeparators = lines.Split(space, StringSplitOptions.RemoveEmptyEntries);
return wordsWithSeparators;
}Text1.txt: Lorem只是印刷和排版行业的虚拟文本。自从1500年代以来,Lorem就一直是业界标准的虚拟文本,当时一台不知名的打印机拿出一台打字机,把它拼成一本样书。它不仅活了五个世纪,而且跨越了电子排版,基本保持不变。它在20世纪60年代被普及,发行了包含Lorem Ipsum段落的Letraset单张,最近还发布了包括Lorem Ipsum版本在内的桌面出版软件Aldus PageMaker。Text2.txt: Lorem只是印刷和排版行业的虚拟文本。自从1500年代以来,Lorem就一直是业界标准的虚拟文本,当时一台不知名的打印机拿出一台打字机,把它拼成一本样书。
发布于 2018-11-27 13:57:55
解决方案的一个例子:(代码很容易理解)您捕获最长的片段和包含它的行
string keeplineoflongestfrag="";
string stlongestfrag="";
int longestfrag = 0;
using (StreamReader file = new StreamReader((filepath, System.Text.Encoding.Default))
{
string line;
char[] space = { ' ' };
while ((line = file.ReadLine()) != null)
{
var wordsWithSeparators = lines.Split(space, StringSplitOptions.RemoveEmptyEntries);
bool modify = false
foreach(var lg in wordsWithSeparators)
{
if (lg.Length > longestfrag)
{
longestfrag = lg.Length;
stlongestfrag = lg;
if (!modify)
{
keeplineoflongestfrag= line ;
modify = true;
}
}
}
}
}https://stackoverflow.com/questions/53500397
复制相似问题