Getline checks if a string is a space

Is there an easy way to check if a string is empty. So I want to check if it contains any white space like \ r \ n \ t and spaces.

thanks

+6
c getline whitespace
source share
7 answers

You can use the isspace function in a loop to check if all characters are empty:

 int is_empty(const char *s) { while (*s != '\0') { if (!isspace((unsigned char)*s)) return 0; s++; } return 1; } 

This function will return 0 if any character is not a space (i.e. the string is not empty) or 1 otherwise.

+15
source share

If the string s consists only of spaces, then strspn(s, " \r\n\t") will return the length of the string. Therefore, an easy way to check strspn(s, " \r\n\t") == strlen(s) , but this will go through the line twice. You can also write a simple function that will move along the line only once:

 bool isempty(const char *s) { while (*s) { if (!isspace(*s)) return false; s++; } return true; } 
+1
source share

I will not check '\ 0' since '\ 0' is not a space and the loop will end there.

 int is_empty(const char *s) { while ( isspace( (unsigned char)*s) ) s++; return *s == '\0' ? 1 : 0; } 
+1
source share

Given char *x=" "; , here is what I can offer:

 bool onlyspaces = true; for(char *y = x; *y != '\0'; ++y) { if(*y != '\n') if(*y != '\t') if(*y != '\r') if(*y != ' ') { onlyspaces = false; break; } } 
0
source share

Consider the following example:

 #include <iostream> #include <ctype.h> bool is_blank(const char* c) { while (*c) { if (!isspace(*c)) return false; c++; } return false; } int main () { char name[256]; std::cout << "Enter your name: "; std::cin.getline (name,256); if (is_blank(name)) std::cout << "No name was given." << std:.endl; return 0; } 
0
source share

My suggestion would be:

 int is_empty(const char *s) { while ( isspace(*s) && s++ ); return !*s; } 

with a working example .

  • Iterates over the characters of a string and stops when
    • a non-spatial symbol was discovered, Arrived
    • or nul.
  • If the line pointer is stopped, check to see if the line string contains the null character.

In the issue of complexity, it is linear with O (n), where n is the size of the input string.

0
source share

For C ++ 11, you can check if a line is a space using std::all_of and isspace (isspace checks for spaces, tabs, new line, vertical tab, feed and carriage return:

 std::string str = " "; std::all_of(str.begin(), str.end(), isspace); //this returns true in this case 

if you really only want to check the character space:

 std::all_of(str.begin(), str.end(), [](const char& c) { return c == ' '; }); 
0
source share

All Articles