有没有一种简单的方法来检查一行是否为空。所以我想检查它是否包含任何空格,如 \r\n\t 和空格。
谢谢
有没有一种简单的方法来检查一行是否为空。所以我想检查它是否包含任何空格,如 \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。
isspace
函数的参数应该强制转换为unsigned char
(is*系列函数不喜欢负数输入,而且char
可能是有符号的):isspace((unsigned char)*s)
。 - pmgint
的参数? - pmors
仅由空格字符组成,则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;
}
*s == '\0' ? 1 : 0
could be simplified to *s == '\0'
- Will Da Silva给定一个 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;
}
str
,*c
,c
哪个是它? :-) - pmgstr
是错误的。*c
是 c
的值,所以没问题!但还是谢谢你! - Rizo可以使用 strspn 一次完成(只需一个布尔表达式):
char *s;
...
( s[ strspn(s, " \r\n\t") ] == '\0' )
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));
我的建议是:
int is_empty(const char *s)
{
while ( isspace(*s) && s++ );
return !*s;
}
带有工作示例。
就复杂性而言,它是线性的O(n),其中n是输入字符串的大小。
对于 C++11,您可以使用 std::all_of
和 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 == ' '; });