strcspn Function

Calculate the number of consecutive characters at the beginning of a string that are not contained in a set of characters.




size_t strcspn(const char *s1, const char *s2);


pointer to the string to be searched
pointer to characters to search for

Return Value

Returns the length of the segment in s1 not containing characters found in s2.


This function will determine the number of consecutive characters from the beginning of s1 that are not contained in s2.


See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

#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.