Is there an easy way 开发者_StackOverflow社区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
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.
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.
- Loops over the characters of the string and stops when
- either a non-space character was found,
- or nul character was visited.
- 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 == ' '; });
This can be done with strspn in one pass (just bool expression):
char *s;
...
( s[ strspn(s, " \r\n\t") ] == '\0' )
You can use sscanf to look for a non-whitespace string of length 1. sscanf will then return -1 if it only finds whitespace.
char test_string[] = " \t\r\n"; // 'blank' example string to be tested
char dummy_string[2]; // holds the first char if it exists
bool isStringOnlyWhiteSpace = (-1 == sscanf(test_string, "%1s", dummy_string));
精彩评论