In this article, you will learn about C string library function strcspn() with example and step by step explanation.

C string library function strcspn()

strcspn is the built in standard library function that is defined under string handling library string.h.

Therefore, we should include string.h header file before using any string library functions.

#include <string.h>

Function prototype of C string library function strcspn()

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

where,

               str1, str2 = strings

This function determines and returns the length of the string str1 that does not contain any character from the second string str2.

strcspn will return the length of the initial segment of str1 if any of the character from str2 matches characters in str1.

This function will return an integer value.

Working of strcspn()

C strcspn()

Let’s get the clear idea from the following program.

[adsense1]

Example: C program to demonstrate the use of C string library function strcspn().

/*Use of string library function strcspn*/

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

int main()
{
   //initialization of char pointers
   const char *str1 = "Learn from trytoprogram.com";
   const char *str2 = "yoyo";

   //displaying both strings
   printf("str1 = %s\n\n", str1);
   printf("str2 = %s\n\n", str2);

   printf("Length of str1 containing "
          "no character from str2 = %d\n", strcspn( str1, str2));

   return 0;
}

Output

c strcspn function

Explanation
In the above program, 'y' from the second string "yoyo" is in the 9th place.

Therefore, strcspn(str1, str2) returns 8 which is the length of non-matching characters in the string "Learn from trytoprogram.com".