The String Equals () method doesn't work, although the two strings are the same in C #

I want to compare whether two strings in C # are equal or not using the Equals () method of the string class. But although both lines are the same, my conditional check failed.

I saw that both lines are equal, and also confirmed this at http://text-compare.com/ . I don’t know what the problem is here ...

My code is:

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

When I set a breakpoint and go step by step looking through each character, then there is a difference in the last currInnerText index. It looks like an empty character. But I already used the Trim () function. This is a picture taken during debugging.

What is the solution to remove a blank character or any other false characters at the end of a currInnerText line?

enter image description here

+8
c #
source share
4 answers

Try to set a breakpoint and check the length. In addition, in some cases, if the locale is not the same, the equals function does not lead to true. Another method you could try (length check) is to print and like this, --- string1 ---, --- string2 ---, so you could see if you have any or trailing spaces. To fix this, you can use string1.trim ()

+8
source share

try it

 String.Equals(currInnerText, paraText, StringComparison.InvariantCultureIgnoreCase); 
+13
source share

In my case, the difference was in a different encoding of the space: one line contained a non-breaking space (160), and the other contained a normal space (32)

it can be solved

 string text1 = "String with non breaking spaces."; text1 = Regex.Replace(text1, @"\u00A0", " "); // now you can compare them 
+10
source share

Before calling .Equals, try the following:

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

This should throw an exception if Equals returns false and should give you an idea of ​​what will happen.

+5
source share

All Articles