C

Function Strcspn() In C – C Tutorial

The strcspn() function searches the main string for the given string and returns the number of characters found until the first matched character is found.

Declaration of strcspn() in C

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

str1 – The primary string to be found
str2 – This string’s characters are searched in the main string until the first matched character is found.

Strcspn function return value ()

This function returns the number of characters found in the main string prior to finding the first matched character.

Example of the C function strcspn()

#include <stdio.h>
#include <string.h>
int main () {
   const char str[20] = "aabbccddeeff"; 
   const char searchString[10] = "dxz";
   int loc;

   /* This function returns the number of characters present in the main string 
    * from beginning till the first matched character is found 
    */
   loc = strcspn(str, searchString);
   printf("The first matched char in string str1 is at: %d", (loc+1));
   return 0;
}

Output:

The first matched char in string str1 is at: 7

The characters in the main string str that we are looking for are ‘d’, ‘x’, and ‘z’; the first matched character is found at position 7 in the main string.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button