C library - strcspn() function



The C library strcspn() function accepts two pointer variables as parameters that calculate the length of the initial segment(str1) and entirely consist of characters not in str2.

Typically, it is used for finding the length of the given string and returns the number of characters from the beginning.

Syntax

Following is the syntax of the C library strcspn() function −

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

Parameters

This function accepts the following parameters −

  • str1 − This is the main C string to be scanned.

  • str2 − This is a string that contains the list of characters matched to str1.

Return Value

This function returns the length of initial segment of string str1 which are not containing any charaters of the string i.e. str2.

Example 1

Following is the C library program that illustrates the strcspn() function to check the first unmatch character from the string.

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

int main () {
   int len;
   // Intializing string(Unmatched Characters)
   const char str1[] = "Tutorialspoint";
   const char str2[] = "Textbook";

   len = strcspn(str1, str2);

   printf("First matched character is at %d\n", len + 1);
   
   return(0);
}

Output

The above code produces the following result −

First matched character is at 10

Example 2

We use the method strcspn() to show the matching character.

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

int main() {
   int size;

   // Intializing string(Matched Characters)
   char str1[] = "tutorialspoint";
   char str2[] = "tutorial"; 
    
   // Using strcspn() to 
   size = strcspn(str1, str2);
    
   printf("The unmatched characters before the first matched character: %d\n", size);
   return 0;
}

Output

The above code produces the following result −

The unmatched characters before the first matched character: 0

Example 3

Here, We are determining the length of the initial segment that does not contain any characters from a given set using the function strcspn().

#include <stdio.h> 
#include <string.h> 
  
int main() {  
   char str1[] = "Welcome to Tutorialspoint Community";  
   char str2[] = "point";  
  
   size_t len = strcspn(str1, str2); 
   // Display the output 
   printf("The length of the initial segment of str1 that does not contain any characters from str2 is: %zu\n", len);  
   return 0;  
}  

Output

The above code produces the following result −

The length of the initial segment of str1 that does not contain any characters from str2 is: 4
Advertisements