How to not include line breaks when comparing two strings
A quick and dirty way, when performance isn't much of an issue:
string1.Replace("\n", "") != string2.Replace("\n", "")
Assuming:
- The sort of direct char-value-for-char-value comparison of != and == is what is wanted here, except for the matter of newlines.
- The strings are, or may, be large enough or compared often enough to make just replacing
"\n"
with an empty string too inefficient.
Then:
public bool LinelessEquals(string x, string y)
{
//deal with quickly handlable cases quickly.
if(ReferenceEquals(x, y))//same instance
return true; // - generally happens often in real code,
//and is a fast check, so always worth doing first.
//We already know they aren't both null as
//ReferenceEquals(null, null) returns true.
if(x == null || y == null)
return false;
IEnumerator<char> eX = x.Where(c => c != '\n').GetEnumerator();
IEnumerator<char> eY = y.Where(c => c != '\n').GetEnumerator();
while(eX.MoveNext())
{
if(!eY.MoveNext()) //y is shorter
return false;
if(ex.Current != ey.Current)
return false;
}
return !ey.MoveNext(); //check if y was longer.
}
This is defined as equality rather than inequality, so you could easily adapt it to be an implementation of IEqualityComparer<string>.Equals
. Your question for a linebreak-less string1 != string2
becomes: !LinelessEquals(string1, string2)
I'd suggest regex to reduce every space
, tab
, \r
, \n
to a single space :
Regex.Replace(string1, @"\s+", " ") != Regex.Replace(string2, @"\s+", " ")