14.6. strspn(), strcspn()

Return the length of a string consisting entirely of a set of characters, or of not a set of characters.

Prototypes

#include <string.h>
size_t strspn(char *str, const char *accept);
size_t strcspn(char *str, const char *reject);

Description

strspn() will tell you the length of a string consisting entirely of the set of characters in accept. That is, it starts walking down str until it finds a character that is not in the set (that is, a character that is not to be accepted), and returns the length of the string so far.

strcspn() works much the same way, except that it walks down str until it finds a character in the reject set (that is, a character that is to be rejected.) It then returns the length of the string so far.

Return Value

The lenght of the string consisting of all characters in accept (for strspn()), or the length of the string consisting of all characters except reject (for strcspn()

Example

char str1[] = "a banana";
char str2[] = "the bolivian navy on manuvers in the south pacific";

// how many letters in str1 until we reach something that's not a vowel?
n = strspn(str1, "aeiou");  // n == 1, just "a"

// how many letters in str1 until we reach something that's not a, b,
// or space?
n = strspn(str1, "ab "); // n == 4, "a ba"

// how many letters in str2 before we get a "y"?
n = strcspn(str2, "y"); // n = 16, "the bolivian nav"

See Also

strchr(), strrchr()