2
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");
4

2 回答 2

8

单线:

int condition = strspn(p, " ") == strlen(p);

稍微优化一下:

int condition = p[strspn(p, " ")] == '\0';
于 2010-07-27T13:39:26.417 回答
1

如果你想要一个快速的方法来做到这一点,我想到的最好的事情就是编写你自己的函数(我假设你只搜索 ' ' 字符)。

int yourOwnFunction(char *str, char c) {
    while(*str != '\0' && *str != c) {
        str++;
    }
    return *str == '\0';
}

所以你只需要测试

if(yourOwnFunction(p,' ')) {
    ...
} else {
    ...
}

如果我误解了什么,请纠正我:)

顺便说一句,我没有测试它,但在最坏的情况下,这应该与其他建议的方法一样快。如果您只想要一个单线 strager(优雅)的解决方案,那就是您的最佳选择!

于 2010-07-27T16:14:26.757 回答