strcspn() in C


The function strcspn() counts the number of characters before first match of characters in both strings. This is declared in “string.h” header file. It returns the number of characters of first string before the occurrence of first matched character.

Here is the syntax of strcspn() in C language,

size_t strcspn(const char *string1, const char *string2)

Here,

string1 − The first string which is to be scanned.

string2 − The second string which is used to search the matching character in first string.

Here is an example of strcspn() in C language,

Example

 Live Demo

#include<stdio.h>
#include<string.h>
int main() {
   char str1[] = "Helloworld!";
   char str2[] = "work";
   int result = strcspn(str1, str2);
   printf("Number of characters before matching character : %d
", (result+1));    return 0; }

Output

Number of characters before matching character : 5

In the above program, two char type arrays are declared and strings are passed to them. The function strcspn() is calculating the number of characters before first match which is “wor”. So, in the first string 5 characters are unmatched. Hence, the output is 5 and which is stored in variable result.

char str1[] = "Helloworld!";
char str2[] = "work";
int result = strcspn(str1, str2);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements