Question

Is there an easy way to check if a line is empty. So i want to check if it contains any white space such as \r\n\t and spaces.

Thanks

Was it helpful?

Solution

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

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 whitespace (i.e. line is not empty), or 1 otherwise.

OTHER TIPS

If a string s consists only of white space characters then strspn(s, " \r\n\t") will return the length of the string. Therefore a simple way to check is strspn(s, " \r\n\t") == strlen(s) but this will traverse the string twice. You can also write a simple function that would traverse at the string only once:

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

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

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

Given a char *x=" "; here is what I can suggest:

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

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;
}

My suggestion would be:

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

with a working example.

  1. Loops over the characters of the string and stops when
    • either a non-space character was found,
    • or nul character was visited.
  2. Where the string pointer has stopped, check if the contains of the string is the nul character.

In matter of complexity, it's linear with O(n), where n the size of the input string.

For C++11 you can check is a string is whitespace using std::all_of and isspace (isspace checks for spaces, tabs, newline, 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 for the character space then:

std::all_of(str.begin(), str.end(), [](const char& c) { return c == ' '; });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top