2010-10-20 67 views
6

是否有一种简单的方法来检查行是否为空。所以我想检查它是否包含任何空格,如\ r \ n \ t和空格。getline检查行是否为空格

感谢

+0

但isspace为()的返回值取决于所安装的C语言环境;因此,根据它可以返回换行或制表符假 – Suba 2017-04-14 08:51:38

回答

15

可以使用isspace功能在一个循环来检查是否所有字符都是空白:

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

如果任何字符不是空格(即行不空),则该函数将返回0,否则返回1。

+2

的参数'isspace'。应该转换为'unsigned char' (is *函数“不喜欢”负输入和'char'可能会被签名):'isspace((unsigned char)* s)' – pmg 2010-10-20 19:48:02

+0

这将工作。谢谢! – Matt 2010-10-20 20:27:59

0

给定一个char *x=" ";这里是我可以建议:

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

如果字符串s只包含空白字符,则strspn(s, " \r\n\t")将返回字符串的长度。因此,一个简单的检查方法是strspn(s, " \r\n\t") == strlen(s),但是这会遍历字符串两次。你也可以写一个简单的函数,将在字符串遍历一次:

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

请看下面的例子:

#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; 
} 
+1

'str','* c','c'这是吗?:-) – pmg 2010-10-20 19:49:50

+0

@pmg:只有'str'是错误的。 '* c'是'c'的值,所以没关系!但是谢谢你! – Rizo 2010-10-20 19:57:30

1

我不会检查“\ 0”,因为“\ 0”不是空间,循环将在那里结束。

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

我的建议是:

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

working example

  1. 循环遍历字符串的字符,当任一非空格字符被发现
    • 停止,
    • 或空字符被访问。
  2. 如果字符串指针已停止,请检查字符串的包含是否为nul字符。

在复杂性方面,它与O(n)成线性关系,其中n是输入字符串的大小。

0

对于C++ 11你可以检查一个字符串是空白使用std::all_ofisspace(isspace为检查空格,制表符,换行符,垂直制表符,和回车:

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

如果你真的只要检查字符空间,然后:

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