C String Functions - C strcspn

Searches a string for a set of characters.

size_t strcspn(const char *str1 , const char *str2 );

Finds the first sequence of characters in the string str1 that does not contain any character specified in str2.

Returns the length of this first sequence of characters found that do not match with str2.


This function has the following parameter.

C string to be scanned.
C string containing the characters to match.


The length of the initial part of str1 not containing any of the characters that are part of str2.


#include <stdio.h>
#include <string.h>
/*from  w ww. j a v  a  2  s. com*/
int main (){
  char str[] = "this is a test 123";
  char keys[] = "1234567890";
  int i;
  i = strcspn (str,keys);
  printf ("The first number in str is at position %d.\n",i+1);
  return 0;


The code above generates the following result.

Example 2

#include <string.h>
#include <stdio.h>
 /*from   ww w. j  av a 2 s  .  co  m*/
int main(void){
    const char *string = "abcde312$#@";
    const char *invalid = "*$#";
    size_t valid_len = strcspn(string, invalid);
    if(valid_len != strlen(string))
       printf("'%s' contains invalid chars starting aa position %zu\n",string, valid_len);

The code above generates the following result.