有哪些技术可以测试字符串是否都是空格?

Evi*_*ach 2 c cstring

char *p = "   woohoo";

int condition = /* some calculation applied to p            */ 
                /* to look for all 0x20/blanks/spaces only  */ 

if (condition)
{
}
else
{
    printf("not ");
}

printf("all spaces\n");
Run Code Online (Sandbox Code Playgroud)

str*_*ger 8

一内胆:

int condition = strspn(p, " ") == strlen(p);
Run Code Online (Sandbox Code Playgroud)

略微优化:

int condition = p[strspn(p, " ")] == '\0';
Run Code Online (Sandbox Code Playgroud)

  • +1第二个是*显着*优化而不是*略*但是,由于这里讨论的原因:http://www.joelonsoftware.com/articles/fog0000000319.html (3认同)