i am comparing updates to two strings. i did a:
string1 != string2
and they turn out different. I put them in the "Add Watch" and i see the only difference is one has line breaks and the other doesnt'.:
string1 = "This is a test. \nThis is a test";
string2 = "This is a test. This is a test";
i basically want to do a compare but dont include line breaks. So if line break is the only difference then consider them equal.
A quick and dirty way, when performance isn't much of an issue:
string1.Replace("\n", "") != string2.Replace("\n", "")
I'd suggest regex to reduce every space
, tab
, \r
, \n
to a single space :
Regex.Replace(string1, @"\s+", " ") != Regex.Replace(string2, @"\s+", " ")
Assuming:
"\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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With