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

Sar*_*nan 9 c#

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

我已经看到两个字符串相同,并在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...
              }
   }
}
Run Code Online (Sandbox Code Playgroud)

当我提出一个断点并逐步完成,看着每一个角色,那么currInnerText最后一个索引就有所不同.它看起来像一个空的char.但我已经使用了Trim()函数.这是在调试过程中捕获的图片.

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

在此输入图像描述

Ste*_* P. 13

试试这个

String.Equals(currInnerText, paraText, StringComparison.InvariantCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)


Ahm*_*mad 10

在我的情况下,差异是空格字符的编码,一个字符串包含不间断空格(160),另一个字符串包含正常空格(32)

它可以解决

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

  • 你救了我的命 ;).谢谢 (2认同)

小智 8

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


aqu*_*nas 5

在致电之前。等于,请尝试以下操作:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果Equals返回false,那应该抛出异常,并且应该告诉您发生了什么。