Check if string is empty or all spaces in C#

前端 未结 5 821
说谎
说谎 2020-12-09 14:32

How to easily check if a string is blank or full of an undetermined amount of spaces, or not?

相关标签:
5条回答
  • 2020-12-09 15:12

    If it's already known to you that the string is not null, and you just want to make sure it's not a blank string use the following:

    public static bool IsEmptyOrWhiteSpace(this string value) =>
      value.All(char.IsWhiteSpace);
    
    0 讨论(0)
  • 2020-12-09 15:16

    If you have .NET 4, use the string.IsNullOrWhiteSpace method:

    if(string.IsNullOrWhiteSpace(myStringValue))
    {
        // ...
    }
    

    If you don't have .NET 4, and you can stand to trim your strings, you could trim it first, then check if it is empty.

    Otherwise, you could look into implementing it yourself:

    .Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts

    0 讨论(0)
  • 2020-12-09 15:19

    Try use LinQ to solve?

    if(from c in yourString where c != ' ' select c).Count() != 0)
    

    This will return true if the string is not all spaces.

    0 讨论(0)
  • 2020-12-09 15:22

    If you literally need to know if the "string is blank or full of an undetermined amount of spaces", use LINQ as @Sonia_yt suggests, but use All() to ensure that you efficiently short-circuit out as soon as you've found a non-space.

    (This is give or take the same as Shimmy's, but answers the OP's question as written to only check for spaces, not any and all whitespace -- \t, \n, \r, etc.)

    /// <summary>
    /// Ensure that the string is either the empty string `""` or contains
    /// *ONLY SPACES* without any other character OR whitespace type.
    /// </summary>
    /// <param name="str">The string to check.</param>
    /// <returns>`true` if string is empty or only made up of spaces. Otherwise `false`.</returns>
    public static bool IsEmptyOrAllSpaces(this string str)
    {
        return null != str && str.All(c => c.Equals(' '));
    }
    

    And to test it in a console app...

    Console.WriteLine("    ".IsEmptyOrAllSpaces());      // true
    Console.WriteLine("".IsEmptyOrAllSpaces());          // true
    Console.WriteLine("  BOO  ".IsEmptyOrAllSpaces());   // false
    
    string testMe = null;
    Console.WriteLine(testMe.IsEmptyOrAllSpaces());      // false
    
    0 讨论(0)
  • 2020-12-09 15:23
    private bool IsNullOrEmptyOrAllSpaces(string str)
    {
        if(str == null || str.Length == 0)
        {
            return true;
        }
    
        for (int i = 0; i < str.Length; i++)
        {
            if (!Char.IsWhiteSpace(str[i])) return false;
        }
    
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题