[英]Comparing two text files in Windows application
我有两个文本框,用户可以在其中输入要比较的文本文件的路径。 当他们进入路径时,我正在执行以下操作,通过逐行读取并最终将它们保存在字符串中来获取每个文件的全部内容。
到目前为止它正在工作,但我需要从文件 2 中取出前 10 个字符,看看这 10 个字符是否存在于文件 1 中。 如果它们存在,则增加一个计数器,否则从文件 2 中转到下一个 10 个字符并在文件 1 中比较它们。 它应该一直持续到 file2 结束。
private void btnCompare_Click(object sender, EventArgs e)
{
string FilePath1 = txtFile1.Text;
string FilePath2 = txtFile2.Text;
string CompleteStringToCompare = "";
string CompleteStringToCompareWith = "";
int counter = 0;
//Read First file
if (!File.Exists(FilePath1))
{
Console.WriteLine("{0} does not exist.", FilePath1);
return;
}
using (StreamReader sr1 = File.OpenText(FilePath1))
{
string input1;
while ((input1 = sr1.ReadLine()) != null)
{
CompleteStringToCompare += input1;
}
}
//Read Second file
if (!File.Exists(FilePath2))
{
Console.WriteLine("{0} does not exist.", FilePath2);
return;
}
using (StreamReader sr2 = File.OpenText(FilePath2))
{
string input2;
while ((input2 = sr2.ReadLine()) != null)
{
CompleteStringToCompareWith += input2;
}
}
}
如何为每 10 个字符循环遍历字符串CompleteStringToCompareWith
并查看字符串CompleteStringToCompare
是否存在那些确切的 10 个字符,直到到达字符串CompleteStringToCompareWith
末尾?
没关系,我确实编写了我需要的其余代码。 这里是:
int length = int.Parse(txtNumberOfChar.Text); //Which is 10 in my case
int j = 1;
string temp = "";
if (CompleteStringToCompareWith != "")
{
int totalSubStrings = CompleteStringToCompareWith.Length / length;
for (int i = 1; i <= totalSubStrings; i++)
{
if (i == totalSubStrings)
temp = CompleteStringToCompareWith.Substring(j, CompleteStringToCompareWith.Length - j);
else
temp = CompleteStringToCompareWith.Substring(j, length);
if (CompleteStringToCompare.Contains(temp))
counter++;
j = j + length;
}
lblMessage.Text = "Total Matches "+ counter;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.