strcspn : <string.h> library function

The function size_t strcspn(const char *str1, const char *str2); scans str1 to find the first occurrence of any of the characters that are part of str2. It returns the length of the prefix of str1 which consists entirely of characters not in str2. If none of the characters of str2 matches with any character of str1, the function will return the length of str1.

Function prototype of strcspn

size_t strcspn(const char *str1, const char *str2);
  • str1 : This is the string to be scanned.
  • str2 : This is the string containing a list of characters to match in str1.

Return value of strcspn

This function returns the length of the initial part of string str1 not containing any of the characters of string str2. If none of the characters of str2 matches with any character of str1, then it return length of string str1.

C program to show the use of strcspn function

The following program shows the use of strcspn function.

#include <stdio.h>
#include <string.h>
#include <conio.h>

int main()
{
   char firstString[100], secondString[100];
   int position;
   
   printf("Enter first string\n");
   scanf("%s", &firstString);
   printf("Enter second string\n");
   scanf("%s", &secondString);
   
   position = strcspn(firstString, secondString);

   printf("Any character of second string matched at %d\n",
        position+1);
   
   getch();
   return(0);
}

Program Output
Enter first string
asdfgAqwE
Enter second string
MNJA
Any character of second string matched at 6