C programming strcspn string.h

size_t strcspn(const char *s1, const char *s2);

s1 -Pointer to first string.

s2 -Pointer to second string.

Return type
size_t -The number of characters that does not match any character of ‘s2’ in ‘s1’.If the two strings has no character in common entirely than the length of ‘s1’ is returned.

In C programming the <string.h> strcspn function returns the number of characters in the string addressed by s1 that does not match any character in the string pointed by ‘s2’.In other words the function return the index of the first character in ‘s1’ that match any character in ‘s2’.A code example is given below.

Code example

char s1[]=”Nameless” , s2[]= “a” , s3[]=”e” , s4[]=”Luffy” , s5[]=”turned” ;

int ret ;

ret = strcspn( s1 , s2);

printf(“ret=%d” , ret);

ret = strcspn(s1 , s3);

printf(“\nret=%d” , ret);

ret = strcspn( s1 , s4);

printf(“\nret=%d” , ret);

ret = strcspn(s1, s5);

printf(“\nret=%d”, ret);



In the first function call s1 and s2 is passed,here the character ‘a’ of s2 matches the second character i.e, the 1 index character-counting starts from 0 index-of s1 so 1 is returned.

In the second call s1 and s3 is passed,the ‘e’ character of s3 matches the first 4th character i.e. the 3rd index character so 3 is returned.

In the third call no character of s1 and s4 matched so the length of s1 pointed string i.e. 8 is returned.

In the fourth call s1 and s5 is passed,here the first character ‘t’ of s5 does not match any character in s1,so the function will take the second character ‘u’ of s5 to search for any matching character in s1,but no ,matching character is found.The function again take the third character ‘r’ to search for that similar character in s1 but again no character is found,this process goes on.The fifth character of s5 ‘e’ however matches the fourth character of s1 i.e. the 3rd index character so 3 is returned.

Related links

->C strchr string.h

->C strpbrk string.h

->C strrchr string.h

->C strspn string.h

->C strstr string.h

->C strtok string.h