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");
Asked
Active
Viewed 209 times
2 Answers
8
One-liner:
int condition = strspn(p, " ") == strlen(p);
Slightly more optimized:
int condition = p[strspn(p, " ")] == '\0';

strager
- 88,763
- 26
- 134
- 176
-
3+1 The second is *significantly* optimised rather than *slightly* though, for the reasons discussed here: http://www.joelonsoftware.com/articles/fog0000000319.html – Clifford Jul 27 '10 at 14:30
-
ya, it logically makes one pass over the string instead of 2. How about an empty string? – EvilTeach Jul 27 '10 at 14:32
-
Ya. this works for my situation. An empty string yields true, which tells me there is no useful information in the cstring. – EvilTeach Jul 27 '10 at 15:00
-
@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 Jul 27 '10 at 15:43
-
Also, the optimized version is less clear to the reader (at least, it's less clear to me on first sight). – strager Jul 27 '10 at 15:44
-
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 Jul 27 '10 at 16:53
-
@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 Jul 27 '10 at 19:41
-
1@strager: w.r.t to clarity; that's what comments are for. An explicit intermediate variable will make it easier to follow too. – Clifford Jul 27 '10 at 19:47
1
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
- 3,765
- 21
- 25
-
It's nice in that it will short circuit out, when a non blank is encountered. – EvilTeach Jul 27 '10 at 16:51