有没有一种简单的方法来检查一行是否为空。所以我想检查它是否包含任何空格,例如 \r\n\t 和空格。
谢谢
您可以isspace
在循环中使用该函数来检查所有字符是否都是空格:
int is_empty(const char *s) {
while (*s != '\0') {
if (!isspace((unsigned char)*s))
return 0;
s++;
}
return 1;
}
如果任何字符不是空格(即行不为空),此函数将返回 0,否则返回 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' 因为 '\0' 不是空格并且循环将在那里结束。
int is_empty(const char *s) {
while ( isspace( (unsigned char)*s) )
s++;
return *s == '\0' ? 1 : 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; }
}
考虑以下示例:
#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;
}
我的建议是:
int is_empty(const char *s)
{
while ( isspace(*s) && s++ );
return !*s;
}
有一个工作示例。
在复杂性方面,它与 O(n) 成线性关系,其中 n 是输入字符串的大小。
对于 C++11,您可以使用std::all_of
and isspace
(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 == ' '; });
这可以通过 strspn 一次性完成(只是 bool 表达式):
char *s;
...
( s[ strspn(s, " \r\n\t") ] == '\0' )