简体   繁体   English

比较C#中的两个字符串

[英]Compare two strings in C#

I store 2 serialized object in 2 text file and then i read both and store it in 2 different string, and try to compare this 2 strings, the comparison failed more then one time because of the carriage return and new line difference in the end of one of the string, how i could compare both with ignoring spaces or carriage returns, I know I can compress the 2 strings and compare them, but is there anything like done by .net library, Like Icomparer, I'm not sure if this will work for me too. 我将2个序列化的对象存储在2个文本文件中,然后读取它们并将其存储在2个不同的字符串中,并尝试比较这2个字符串,由于回车和换行符结尾的不同,比较失败了一次以上字符串之一,我如何将它们与忽略空格或回车符进行比较,我知道我可以压缩2个字符串并进行比较,但是是否有类似.net库那样的东西,例如Icomparer,我不确定这是否也会为我工作。

thank you in advance Jp 预先感谢您Jp

If both values are stored as strings, the String.Trim() function will take care of your troublesome whitespace characters, or just compare whilst replacing the whitespace characters. 如果两个值都存储为字符串,则String.Trim()函数将处理麻烦的空白字符,或者仅在替换空白字符时进行比较。

        string a = "string comparison\r\n";
        string b = "string comparison";

        string c = a.Trim();
        string d = b.Trim();

        if (c == d)
            Console.WriteLine("strings are equal");
        else
            Console.WriteLine("strings are not equal");

        string e = a.Replace("\r\n", "");
        string f = b.Replace("\r\n", "");

        if (e == f)
            Console.WriteLine("strings are equal");
        else
            Console.WriteLine("strings are not equal");

一种快速的解决方法是将所有'\\ n'和'\\ r'字符替换为零,然后进行比较。

If you're reading line by line, just ignore any characters that represent line breaks between them. 如果要逐行阅读,请忽略任何表示它们之间的换行符。 If you expect line breaks, simply convert to identical characters using a find and replace. 如果您希望换行,只需使用查找和替换将其转换为相同的字符。

You can use a simple Regular Expression that can eliminate the whitespace and compare (or do what Phillippe said). 您可以使用一个简单的正则表达式来消除空白并进行比较(或执行Phillippe所说的)。 But I dont think there a built-in function to do that kind of comparison. 但是我认为没有内置函数可以进行这种比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM