Why string.IsNullOrWhiteSpace(“\0”) is false

前端 未结 6 1811
不思量自难忘°
不思量自难忘° 2021-01-18 13:17

I faced a problem where invisible character \\0 which is pretty like a \'white space\' not considered as white space by the string.IsNullOrWhiteSpace method. I

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 13:45

    Create an extension method which adds the null char as a check.

    public bool IsNullOrWhitespaceOrHasNullChar(this string text)
    {
       return string.IsNullOrWhiteSpace(text) || Regex.IsMatch(text, "\0");
    }
    

    Note it the null char exists anywhere in the string, it will be found and reported as such, so a string with "a\0" would return true. If that is a concern create a test which checks for a full string of \0.

提交回复
热议问题