Compare two strings ignoring new line characters and white spaces

how about:

string stringOne = "ThE    OlYmpics 2012!";
string stringTwo = "THe\r\n        OlympiCs 2012!";

string fixedStringOne = Regex.Replace(stringOne, @"\s+", String.Empty);
string fixedStringTwo = Regex.Replace(stringTwo, @"\s+", String.Empty);

bool isEqual = String.Equals(fixedStringOne, fixedStringTwo,
                              StringComparison.OrdinalIgnoreCase);

Console.WriteLine(isEqual);
Console.Read();

An alternative approach is to use the CompareOptions of String.Compare.

CompareOptions.IgnoreSymbols

Indicates that the string comparison must ignore symbols, such as white-space characters, punctuation, currency symbols, the percent sign, mathematical symbols, the ampersand, and so on.

String.Compare("foo\r\n   ", "foo", CompareOptions.IgnoreSymbols);

https://docs.microsoft.com/en-us/dotnet/api/system.globalization.compareoptions


copy the string then

xyz.Replace(" ", string.Empty);
xyz.Replace("\n", string.Empty);

Tags:

C#

.Net

String