C ++ checks if a string is a space or null

Basically, I have a line of spaces " " or blocks of spaces or "" empty on some lines of files, and I would like to know if there is a function in C ++ that checks this.

* note : * As a side issue, in C ++, if I want to break a string and check it against a template, which library should I use? If I want to encode it myself, what basic functions do I need to know to manipulate a string? Are there any good links?

+4
source share
6 answers

Since you did not specify character interpretation> 0x7f , I assume ASCII (i.e. there are 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
source
 std::string str = ...; if (str.empty() || str == " ") { // It empty or a single space. } 
+5
source
 bool isWhitespace(std::string s){ for(int index = 0; index < s.length(); index++){ if(!std::isspace(s[index])) return false; } return true; } 
+3
source
  std::string mystr = "hello"; if(mystr == " " || mystr == "") //do something 

When breaking down a string, std::stringstream may be useful.

+2
source

You do not have a null line in some lines of files.

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

You can use for example. std::string.length , or if you like C better, strlen .

The isspace function isspace convenient for checking spaces, but note that for char characters, the argument must be distinguished to an unsigned char , for example, from a cuff,

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

Cheers and hth.,

+2
source

If you need template validation, use regexp.

-2
source

All Articles