字符串Equals()方法失败,即使C#中的两个字符串相同?

我想使用字符串类的Equals()方法比较C#中的两个字符串是否相等。 但即使两个字符串都相同,我的条件检查也会失败。

我已经看到两个字符串相同,并在http://text-compare.com/网站上validation了这一点。 我不知道这里有什么问题……

我的代码是:

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最后一个索引就有所不同。 它看起来像一个空的char。 但我已经使用了Trim()函数。 这是在调试过程中捕获的图片。

在currInnerText字符串末尾删除空char或任何其他虚假字符的解决方案是什么?

在此处输入图像描述

尝试放置一个断点并检查长度。 此外,在某些情况下,如果语言环境不相同,则equals函数不会生成true。 你可以尝试的另一种方法(检查长度)是这样打印— string1 —,— string2 —,这样,你可以看到你是否有任何尾随空格。 要解决此问题,您可以使用string1.trim()

试试这个

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

在我的例子中,区别在于空格字符的编码,一个字符串包含不间断空格(160),另一个字符串包含正常空格(32)

它可以解决

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

在你打电话给.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,那么应该抛出一个exception,并且应该让你知道发生了什么。