views:

343

answers:

4

At work today we were trying to come up with any reason you would use strspn.

I searched google code to see if it's ever been implemented in a useful way and came up blank. I just can't imagine a situation in which I would really need to know the length of the first segment of a string that contains only characters from another string. Any ideas?

+1  A: 

It's based on the the ANSI C function strspn(). It can be useful in low-level C parsing code, where there is no high-level string class. It's considerably less useful in PHP, which has lots of useful string parsing functions.

Adam Rosenfield
A: 

Well, by my understanding, its the same thing as this regex:

^[set]*

Where set is the string containing the characters to be found.

You could use it to search for any number or text at the beginning of a string and split.

It seems it would be useful when porting code to php.

Loki
more like ^[set]*
Arkadiy
+4  A: 

Although you link to the PHP manual, the strspn() function comes from C libraries, along with strlen(), strcpy(), strcmp(), etc.

strspn() is a convenient alternative to picking through a string character by character, testing if the characters match one of a set of values. It's useful when writing tokenizers. The alternative to strspn() would be lots of repetitive and error-prone code like the following:

for (p = stringbuf; *p; p++) {
  if (*p == 'a' || *p == 'b' || *p = 'c' ... || *p == 'z') {
    /* still parsing current token */
  }
}

Can you spot the error? :-)

Of course in a language with builtin support for regular expression matching, strspn() makes little sense. But when writing a rudimentary parser for a DSL in C, it's pretty nifty.

Bill Karwin
spotted: *p = 'c' is probably not what you ment ;-)
Christian.K
A: 

It is useful specificaly for functions like atoi - where you have a string you want to convert to a number, and you don't want to deal with anything that isn't in the set "-.0123456789"

But yes, it has limited use.

Adam Davis