C Standard Library

C <string.h> - strspn() Function



The C <string.h> strspn() function returns the length of maximum initial segment (span) of the byte string pointed to by str1 which consists of only the characters present in the byte string pointed to by str2.

Syntax

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

Parameters

str1 Specify pointer to the null-terminated byte string to be scanned.
str2 Specify pointer to the null-terminated byte string containing the characters to match.

Return Value

Returns the length of maximum initial segment of str1 which consists of only the characters present in str2.

Example:

The example below shows the usage of strspn() function.

#include <stdio.h>
#include <string.h>
 
int main (){
  char str1[100] = "12345ABWzx3423Sx";
  char str2[100] = "1234567890";
  
  //finding the length of maximum initial segment
  //of str1 containing only the characters of str2
  int max_initial_len = strspn(str1, str2);

  //displaying the result
  printf("Length of maximum initial length: %d\n",
        max_initial_len);
 
  return 0;
}

The output of the above code will be:

Length of maximum initial length: 5

❮ C <string.h> Library