This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.
Released under the GNU General Public License.
strcspn
Prototype
#include <string.h>
size_t strcspn(const char *s, const char *set);
Description
Returns the length of the maximum initial segment of the string s
which consists entirely of characters not from the string set
.
Implementation
#include <string.h>
size_t strcspn(const char *s, const char *set)
{
const char *sp1, *sp2;
for (sp1 = s; *sp1 != '\0'; ++sp1)
for (sp2 = set; *sp2 != '\0'; ++sp2)
if (*sp1 == *sp2)
return sp1 - s;
return sp1 - s;
}
Example
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Extract the next white space separated tokenfrom the `s' string.
*/
char *tokenize(char *buf, const char **s)
{
size_t size;
while (isspace(**s))
++*s;
size = strcspn(*s, "\t\v\f\r\n ");
if (size < 1)
return NULL;
strncpy(buf, *s, size);
buf[size] = '\0';
*s += size;
return buf;
}
int main(void)
{
const char *s = "test string\na b\t c ";
char buf[128];
while (tokenize(buf, &s) != NULL)
printf("token = \"%s\"\n", buf);
return EXIT_SUCCESS;
}
References
ISO C 9899:1990 7.11.5.3