strspn : <string.h> library function

The function size_t strspn(const char *str1, const char *str2); returns the length of the initial portion of str1(prefix) which consists entirely of characters that are part of str2. The search does not include the terminating null-characters('\0') of both strings.

Function prototype of strspn

size_t strspn(const char *str1, const char *str2);
  • str1 : A pointer to a string to be scanned.
  • str2 : A pointer to a string containing the list of characters to match.

Return value of strspn

This function returns the length of the initial portion(prefix) of str1 containing only characters from str2.

C program to show the use of strspn function

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

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

   printf("Length of string matched is %d\n",length);
   
   getch();
   return(0);
}

Program Output
Enter first string
ABADCALKJHG
Enter second string
ABCD
Length of string matched is 6