Calculate the number of consecutive characters at the beginning of a string that are not contained in a set of characters.
Include
<string.h>
Prototype
size_t strcspn(const char *s1, const char
*s2);
Arguments
s1
s2
Return Value
Returns the length of the segment in s1
not containing
characters found in s2
.
Remarks
This function will determine the number of consecutive characters from the
beginning of s1
that are not contained in s2
.
Example
#include <string.h>
#include <stdio.h>
int main(void)
{
char str1[20] = "hello";
char str2[20] = "aeiou";
char str3[20] = "animal";
char str4[20] = "xyz";
int res;
res = strcspn(str1, str2);
printf("strcspn(\"%s\", \"%s\") = %d\n",
str1, str2, res);
res = strcspn(str3, str2);
printf("strcspn(\"%s\", \"%s\") = %d\n",
str3, str2, res);
res = strcspn(str3, str4);
printf("strcspn(\"%s\", \"%s\") = %d\n",
str3, str4, res);
}
Example Output
strcspn("hello", "aeiou") = 1
strcspn("animal", "aeiou") = 0
strcspn("animal", "xyz") = 6
Example Explanation
In the first result, e
is in s2
so it stops
counting after h
.
In the second result, a
is in s2
.
In the third result, none of the characters of s1
are in
s2
so all characters are counted.