2012-09-27 15 views
5

我想使用字符串類的Equals()方法比較兩個字符串在C#中是否相等。但即使兩個字符串都相同,我的條件檢查失敗。即使這兩個字符串在C#中是相同的,String Equals()方法也會失敗?

我看到兩個字符串都是相同的,並且在http://text-compare.com/網站上對此進行了驗證。我不知道什麼是這裏的問題...

我的代碼是:

protected string getInnerParaOnly(DocumentFormat.OpenXml.Wordprocessing.Paragraph currPara, string paraText) 
     { 
      string currInnerText = ""; 
      bool isChildRun = false; 

     XmlDocument xDoc = new XmlDocument(); 
     xDoc.LoadXml(currPara.OuterXml); 
     XmlNode newNode = xDoc.DocumentElement; 

     string temp = currPara.OuterXml.ToString().Trim(); 

     XmlNodeList pNode = xDoc.GetElementsByTagName("w:p"); 
     for (int i = 0; i < pNode.Count; i++) 
     { 
      if (i == 0) 
      { 
       XmlNodeList childList = pNode[i].ChildNodes; 
       foreach (XmlNode xNode in childList) 
       { 
        if (xNode.Name == "w:r") 
        { 
         XmlNodeList childList1 = xNode.ChildNodes; 
         foreach (XmlNode xNode1 in childList1) 
         { 
          if (xNode1.Name == "w:t" && xNode1.Name != "w:pict") 
          { 
           currInnerText = currInnerText + xNode1.InnerText; 
          } 
         } 
        } 
       } 
       if (currInnerText.Equals(paraText)) 
       { 
        //do lot of work here... 
       } 
    } 
} 

當我把一個破發點並走一步看一步通過,看着每一個字符,則有是currInnerText最後一個索引的差異。它看起來像一個空的字符。但是我已經使用了Trim()函數。這是在調試過程中捕獲的圖片。

刪除空字符或currInnerText字符串末尾的其他虛假字符的解決方案是什麼?

enter image description here

+10

這不是你的實際代碼(在C#中'Equals()'不是全部小寫)。請粘貼您的實際代碼。 – BoltClock

+0

顯然你沒有告訴我們。如果您比較兩個相同的字符串,那麼您提供的代碼肯定會有效。我們需要看到更多的代碼。 –

+1

你的琴絃是什麼? – SeToY

回答

7

嘗試把一個斷點,並檢查長度。此外,在某些情況下,如果語言環境不相同,則等號函數不會導致錯誤。你可以嘗試的另一種方法(檢查長度)是這樣打印的--- string1 ---,--- string2 ---,這樣,你可以看到是否有任何尾隨空格。爲了解決這個問題,你可以使用string1.trim()

+0

謝謝...我會檢查它 – Saravanan

10

試試這個

String.Equals(currInnerText, paraText, StringComparison.InvariantCultureIgnoreCase); 
3

在打電話之前,.Equals,試試這個:

if (currInnerText.Length != paraText.Length) 
    throw new Exception("Well here's the problem"); 

for (int i = 0; i < currInnerText.Length; i++) { 
    if (currInnerText[i] != paraText[i]) { 
     throw new Exception("Difference at character: " + i+1); 
    } 
} 

如果equals返回FALSE的時候拋出一個異常應該給你一個想法是什麼。

+0

:謝謝你的可愛的跟蹤技術...我明天更新你 – Saravanan

8

在我的情況差異空格字符的編碼,一個字符串包含非間斷空間(160),另一種含有正常空間(32)

它可以通過

string text1 = "String with non breaking spaces."; 
text1 = Regex.Replace(text1, @"\u00A0", " "); 
// now you can compare them 
可以解決
+2

你救了我的生命;)。謝謝 –

+1

這對我有用。在我的情況下,我從db讀取一個文本,然後在程序中創建另一個文本,然後匹配兩個文本。 –

相關問題