C# string comparison ignoring spaces, carriage return or line breaks

前端 未结 10 942
执念已碎
执念已碎 2020-12-05 13:07

How can I compare 2 strings in C# ignoring the case, spaces and any line-breaks. I also need to check if both strings are null then they are marked as same.

Thanks!<

10条回答
  •  隐瞒了意图╮
    2020-12-05 13:42

    An approach not optimized for performance, but for completeness.

    • normalizes null
    • normalizes unicode, combining characters, diacritics
    • normalizes new lines
    • normalizes white space
    • normalizes casing

    code snippet:

    public static class StringHelper
    {
        public static bool AreEquivalent(string source, string target)
        {
            if (source == null) return target == null;
            if (target == null) return false;
            var normForm1 = Normalize(source);
            var normForm2 = Normalize(target);
            return string.Equals(normForm1, normForm2);
        }
    
        private static string Normalize(string value)
        {
            Debug.Assert(value != null);
            // normalize unicode, combining characters, diacritics
            value = value.Normalize(NormalizationForm.FormC);
            // normalize new lines to white space
            value = value.Replace("\r\n", "\n").Replace("\r", "\n");
            // normalize white space
            value = Regex.Replace(value, @"\s", string.Empty);
            // normalize casing
            return value.ToLowerInvariant();
        }
    }
    

提交回复
热议问题