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

前端 未结 4 922
不知归路
不知归路 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: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!

提交回复
热议问题