6
A
回答
15
可以使用isspace
功能在一个循环来检查是否所有字符都是空白:
int is_empty(const char *s) {
while (*s != '\0') {
if (!isspace((unsigned char)*s))
return 0;
s++;
}
return 1;
}
如果任何字符不是空格(即行不空),则该函数将返回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; }
}
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
我不会检查“\ 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;
}
- 循环遍历字符串的字符,当任一非空格字符被发现
- 停止,
- 或空字符被访问。
- 如果字符串指针已停止,请检查字符串的包含是否为nul字符。
在复杂性方面,它与O(n)成线性关系,其中n是输入字符串的大小。
0
对于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 == ' '; });
相关问题
- 1. 检查表行是否为空
- 2. 检查JTextField是否为空
- 3. 检查stderr是否为空
- 4. 检查NumericUpDown是否为空
- 5. laravel检查是否为空
- 6. 检查imageView是否为空
- 7. 检查表是否为空
- 8. 检查CheckedListBox是否为空
- 9. 检查JValue是否为空
- 10. 检查StringBuffer是否为空
- 11. 检查是否为空DataRow
- 12. 检查是否为空VB.NET
- 13. 检查ListView是否为空
- 14. 检查TextView是否为空?
- 15. 检查tabControl1是否为空?
- 16. 检查流是否为空
- 17. 检查它是否为空
- 18. 检查textarea是否为空
- 19. 检查innerHTML是否为空
- 20. 检查CSV是否为空
- 21. 检查std :: wstring是否为空或空
- 22. 检查列是否为空或空
- 23. 检查属性是否存在与检查是否为空
- 24. c# - 检查数组的位置是否为空或空格?
- 25. 使用jQuery,如何检查表格单元格是否为空?
- 26. 使用JavaScript检查HTML表格单元格是否为空?
- 27. ASP.NET检查是否为LoginName为空
- 28. 检查命令行参数是否为空/空
- 29. JQuery检查输入是否为空而不是检查onload?
- 30. mvc 4 IEnumerable检查是否为空
但isspace为()的返回值取决于所安装的C语言环境;因此,根据它可以返回换行或制表符假 – Suba 2017-04-14 08:51:38