#include <string.h> size_t strcspn(const char *str, const char *cset);
strcspn
locates the first character in the first argument string
(str
) contained in the second argument string (cset
),
returning its position in the first argument.
strcspn
returns the number of consecutive characters not in the
given character set found in the argument string, starting at the first
character. If all characters of the string are not in the set (so that
no character in the set can be found), the value returned is the length
of the string. Similarly, if the character set is null (that is, if it
contains no characters), the return value from strcspn
is the
length of the first argument.
See the memscntb
function description for information on possible
interactions between the strcspn
, memscntb
, or
strscntb
functions.
#include <string.h> #include <stdio.h> #define MAXLINE 100 main() { char text[MAXLINE+1]; size_t pos, len; int words; for (;;) { puts("Enter a line of text."); puts("Just press Enter to quit."); gets(text); if (text[0] == '0') exit(0); /* Quit if null input. */ pos = 0; words = 0; for (;;) { /* Skip to next punctuation mark. */ len = strcspn(text+pos, " .,?!"); /* if next character is punctuation */ if (len == 0) { ++pos; continue; /* Skip to next character. */ } /* encountered the end of the string */ if (text[pos+len] == '0') break; if (words == 0) puts("The words in the input line are:"); ++words; do{ putchar(text[pos]); ++pos; } while(--len); putchar('n'); ++pos; /* Skip the punctuation. */ } if (words == 0) puts("There were no words in that line."); } }
strrcspn
, strscan
, strspn