How do I make my string compare not sensitive to (ignore) minor differences in white space?

前端 未结 4 908
不知归路
不知归路 2020-12-10 06:11

I have some tests that check strings that are displayed to the user.

I don’t wish the test to fail to due to changes in the indentations or line breaks etc. So I am

相关标签:
4条回答
  • 2020-12-10 06:45

    You can use CompareOptions:

    String.Compare(a, b, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols);
    

    Extract from MSDN:

    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.

    0 讨论(0)
  • 2020-12-10 06:50

    Writing a custom compare would be tricky if you need it just to do this for whitespace. I would suggest using regex to normalize, i.e.

    private static readonly Regex normalizeSpace =
            new Regex(@"\s+", RegexOptions.Compiled);
    ...
    string s = normalizeSpace.Replace(input, " ");
    

    Obviously normalize both operands and then test for equality as normal.

    0 讨论(0)
  • 2020-12-10 06:54

    I wrote a small function that trims the input-string both at the start and at the end. Then it goes in a loop to check for double spaces and while there are double spaces, it will replace them by one. So at the end you'll only keep one space.

    private static string RemoveSpaces(string input)
    {
        input = input.Trim();
        while (input.Contains("  "))
            input = input.Replace("  ", " ");
        return input;
    }
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-10 06:58

    You can also use the following custom function

            public static string ExceptChars(this string str, IEnumerable<char> toExclude)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < str.Length; i++)
                {
                    char c = str[i];
                    if (!toExclude.Contains(c))
                        sb.Append(c);
                }
                return sb.ToString();
            }
    
            public static bool SpaceInsenstiveComparision(this string stringa, string stringb)
            {
                return stringa.ExceptChars(new[] { ' ', '\t', '\n', '\r' }).Equals(stringb.ExceptChars(new[] { ' ', '\t', '\n', '\r' }));
            }
    

    And then use it following way

    "Te  st".SpaceInsenstiveComparision("Te st");
    
    0 讨论(0)
提交回复
热议问题