Hi Rene, Derek, On 2026-05-08T07:47:15-0400, Derek Martin wrote: > On Fri, May 08, 2026 at 08:08:13AM +0200, Rene Kita wrote: > > strspn is one of those function I can't get into my head, that's why I > > always end with a loop. :-) I should really try to remember it. > > I prefer the loop: They're functionally equivalent, nearly as > succinct, and far more explicit. you're not the only one who has > trouble remembering it. In professional production code I've seen > loops far more often than strspn. Its name doesn't really lend to one > remembering what it does, like a lot of the less-commonly-used C > library functions. =8^)
The name means "string span". It is the span (length) of the substring
composed exclusively of characters in the second parameter.
I believe it's not often used because few people know it, and thus few
people spread the knowledge of when it's useful and how.
There are mainly two cases where it's useful:
- Skip leading characters (often, white space, or other delimiters).
s += strspn(s, " \t"); // skip white space
s += strspn(s, "/"); // skip path delimiters
- A boolean indicator for whether a string starts with some character.
if (strspn(s, "/"))
handle_absolute_path(s);
else
handle_relative_path(s);
Then there are a few other cases, but these two cover the most common
ones. Once you learn this function, it crams a lot of logic into a
single function, making the code more compact and readable. I find it
to be one of the most useful string functions.
Another very useful and rarely used one is strpbrk(3). That is
strchr(3) on steroids. (And a better name for it might have been
strchrs(), as Plan9 called it.)
Have a lovely day!
Alex
--
<https://www.alejandro-colomar.es>
signature.asc
Description: PGP signature
