What techniques are available to test if a character string is all spaces?
char *p = " woohoo";
int condition = /* some calculation applied to p */
/* to look for all 0x20/blanks/spaces only */
if (condition)
{
开发者_JAVA百科}
else
{
printf("not ");
}
printf("all spaces\n");
One-liner:
int condition = strspn(p, " ") == strlen(p);
Slightly more optimized:
int condition = p[strspn(p, " ")] == '\0';
If you want a fast way to do this, the best thing that comes to my mind is to write your own function (I assume you only search for ' ' characters) .
int yourOwnFunction(char *str, char c) {
while(*str != '\0' && *str != c) {
str++;
}
return *str == '\0';
}
So you just have to test
if(yourOwnFunction(p,' ')) {
...
} else {
...
}
Correct me if I misunderstood something :)
Btw I didn't test it, but this should be in the worst case as fast as the other proposed method. If you just want a one-liner strager's (elegant) solution is the way to go!
精彩评论