C programming strspn string.h


In C programming the <string.h> strspn function the length of the string that contain only the character from the other string.A more detail explanation is given below.The declaration of the function is given below.

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

Parameters:
s1 -The first string.

s2 -The second string.The first string ‘s1’ characters is match to the characters of this string.

Return type
char* -The length of the segment.If all characters of s1 occur in s2 then the length of s1 is returned,same as strlen(s1).

The first thing to note is the characters of ‘s1’ is compare to the characters of ‘s2’ not vice-versa.

Second-Matching the characters does not mean they have to occur in the same order.For instance say,s1=”string”,s2=”apes”, the first character ‘s’ of s1 matches that of the last character in s2,so ‘s’ are both present in s1 and s2,’t’ of s1 is not present in ‘s2’ so here the returned value is 1.

Third-The other way of putting the workings of ‘strspn’ is,it returns the index of the first character in ‘s1’ that does not match any character in ‘s2’.Note here the returned value is the index value so counting starts from 0.

A code example is givne below.

Code example

char s1[] =”Racecar” , s2[] =”Racer” , s3[]=”ace” , s4[]=”bell” , ret ;

ret = strspn(s1 , s2);

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

ret = strspn(s1 , s3);

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

ret =strspn(s1 , s4);

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

Output,

ret=7
ret=0
ret=0

Look at the output,for the first output all the characters of s1 is present in s2 so the returned value is the length of s1.

For the second output,the first character of s1 ‘R’ deos not occur in s3 so the index value of ‘R’ in s1 i.e. 0 is returned.Although here the second character ‘a’ of s1 occur in s3,it is not taken into account cause the function try to match the character starting from the first character and since it could not find any matching character,it’s index is returned.

Similarly,for the third output,the first character ‘R’ of s1 is not found in ‘s4’ so the index of ‘R’ in s1 is returned.


Related links

->C strcspn string.h

->C strpbrk string.h

->C strrchr string.h

->C strchr string.h

->C strstr string.h

->C strtok string.h