tags:

views:

126

answers:

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");
+8  A: 

One-liner:

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

Slightly more optimized:

int condition = p[strspn(p, " ")] == '\0';
strager
+1 The second is *significantly* optimised rather than *slightly* though, for the reasons discussed here: http://www.joelonsoftware.com/articles/fog0000000319.html
Clifford
ya, it logically makes one pass over the string instead of 2.How about an empty string?
EvilTeach
Ya. this works for my situation. An empty string yields true, which tells me there is no useful information in the cstring.
EvilTeach
@Clifford, For practical purposes, it's only slightly faster. Except for very large strings, I doubt there will be a difference, even with a million calls. Feel free to benchmark to prove me wrong.
strager
Also, the optimized version is less clear to the reader (at least, it's less clear to me on first sight).
strager
It's a plus one sort of answer, in that there are people who have not run into strspn before. That's part of what the question is for; New Ideas. I had settled on the first example. Then decided to ask the question. I have switched to the second example in my actual code.
EvilTeach
@strager: For large strings..., or a large number of small strings in an iteration. I guess you did not read the article in the link!? If it takes twice as long, it is true that you will not notice the difference between say 2 and 4 microseconds, but that is not the point at all.
Clifford
@strager: w.r.t to clarity; that's what comments are for. An explicit intermediate variable will make it easier to follow too.
Clifford
+1  A: 

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!

George B.
It's nice in that it will short circuit out, when a non blank is encountered.
EvilTeach