C++ check if string is space or null

后端 未结 6 1247
死守一世寂寞
死守一世寂寞 2021-01-13 04:38

Basically I have string of whitespace \" \" or blocks of whitespace or \"\" empty in some of the lines of the files and I would

相关标签:
6条回答
  • 2021-01-13 05:07
     std::string mystr = "hello";
    
     if(mystr == " " || mystr == "")
       //do something
    

    In breaking a string down, std::stringstream can be helpful.

    0 讨论(0)
  • 2021-01-13 05:07

    If you want pattern checking use regexp.

    0 讨论(0)
  • 2021-01-13 05:23

    Since you haven't specified an interpretation of characters > 0x7f, I'm assuming ASCII (i.e. no high characters in the string).

    #include <string>
    #include <cctype>
    
    // Returns false if the string contains any non-whitespace characters
    // Returns false if the string contains any non-ASCII characters
    bool is_only_ascii_whitespace( const std::string& str )
    {
        auto it = str.begin();
        do {
            if (it == str.end()) return true;
        } while (*it >= 0 && *it <= 0x7f && std::isspace(*(it++)));
                 // one of these conditions will be optimized away by the compiler,
                 // which one depends on whether char is signed or not
        return false;
    }
    
    0 讨论(0)
  • 2021-01-13 05:23
    bool isWhitespace(std::string s){
        for(int index = 0; index < s.length(); index++){
            if(!std::isspace(s[index]))
                return false;
        }
        return true;
    }
    
    0 讨论(0)
  • 2021-01-13 05:26

    You don't have a nullstring "in some of the lines of the files".

    But you can have an empty string, i.e. an empty line.

    You can use e.g. std::string.length, or if you like C better, strlen function.

    In order to check for whitespace, the isspace function is handy, but note that for char characters the argument should be casted to unsigned char, e.g., off the cuff,

    bool isSpace( char c )
    {
        typedef unsigned char UChar;
        return bool( ::isspace( UChar( c ) ) );
    }
    

    Cheers & hth.,

    0 讨论(0)
  • 2021-01-13 05:28
    std::string str = ...;
    if (str.empty() || str == " ") {
        // It's empty or a single space.
    }
    
    0 讨论(0)
提交回复
热议问题