2012-03-29 61 views
-7

我有兩個文本框,其中用戶輸入他們的路徑來比較文本文件。當他們進入路徑時,我正在通過逐行閱讀並最終將它們保存爲字符串來獲取每個文件的全部內容。到目前爲止,它正在工作,但我需要從file2中取前10個字符,看看這10個字符是否存在於file1中,如果存在,則增加計數器,否則轉到file2中接下來的10個字符,並比較在file1中的內容。它應該繼續,直到file2結束。在Windows應用程序中比較兩個文本文件

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; 
       } 

      } 

沒關係,我確實編寫了我需要的其餘代碼。那就是:

  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; 
      } 
+7

在哪裏的問題? – 2012-03-29 17:12:24

+0

我的問題是如何循環字符串「CompleteStringToCompareWith」每10個字符,並查看這些確切的10個字符是否存在字符串「CompleteStringToCompare」,直到到達字符串「CompleteStringToCompareWith」的末尾 – Tiger 2012-03-29 17:33:49

+1

你有沒有嘗試自己嘗試一下嗎?我沒有看到你發佈的任何代碼,甚至接近這樣做。 – 2012-03-29 17:36:30

回答

1
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; 
      }