10

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

谢谢

4

8 回答 8

23

您可以isspace在循环中使用该函数来检查所有字符是否都是空格:

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

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

于 2010-10-20T19:32:31.173 回答
3

如果字符串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;
}
于 2010-10-20T19:32:48.627 回答
1

我不会检查 '\0' 因为 '\0' 不是空格并且循环将在那里结束。

int is_empty(const char *s) {
  while ( isspace( (unsigned char)*s) )
          s++;
  return *s == '\0' ? 1 : 0;
}
于 2010-10-21T00:59:55.393 回答
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; }
}
于 2010-10-20T19:29:05.360 回答
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;
}
于 2010-10-20T19:41:04.007 回答
0

我的建议是:

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

有一个工作示例

  1. 循环遍历字符串的字符并在何时停止
    • 找到非空格字符,
    • 或 nul 字符被访问。
  2. 在字符串指针停止的地方,检查字符串的包含是否为空字符。

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

于 2015-07-16T11:50:49.350 回答
0

对于 C++11,您可以使用std::all_ofand 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 == ' '; });
于 2016-09-08T12:21:10.450 回答
0

这可以通过 strspn 一次性完成(只是 bool 表达式):

char *s;
...
( s[ strspn(s, " \r\n\t") ] == '\0' )
于 2021-07-18T19:20:43.260 回答