In this article, you will learn in-depth about C string library function strspn( ) with example and explanation.
strspn( )
is the built in standard string manipulation function that is defined under string handling library string.h
.
Therefore it is necessary to include string header file to use standard C string library function strspn( )
.
#include<string.h>
size_t strspn( const char *str1, const char *str2 );
where,
str1 = string that needs to be scanned
str2 = string which character needs to be matched in str1
This function searches for the characters of string str2
in the string str1
.
It returns the length of the initial part of the string str1
that contains only characters from the string str2
.
Therefore, it returns an integer value.
[adsense1]
/*Use of string library function strspn*/
#include<stdio.h>
#include<string.h>
int main()
{
//initializing char pointers
const char *str1 = "Learn from trytoprogram.com";
const char *str2 = "rtyn eaL ofm";
//displaying both string
printf("str1 = %s\n\n", str1);
printf("str2 = %s\n\n", str2);
printf("Length of str1 consisting only characters "
"from str2 = %d\n", strspn( str1, str2 ));
return 0;
}
Output
Explanation
In the above, function strspn( )
searches for "rtyn eaL ofm"
in the string str1
.
Thus, it returns the total length of matching characters as shown in the figure above.