Introduction
C is a procedure-oriented programming language created by Dennis Ritchie in 1972. C language provides us with multiple string functions that can save us from writing many lines of code. We can use the default functions instead of the long codes to get our work done. The string functions are included in the "string.h"header file.
In this article, let’s learn about a string function - strspn().
strspn()
The strspn() is a C function that returns the length of the starting substring of the string referenced to by string1 that contains just the characters from the string pointed to by string2. Let’s learn how to use strspn() with an example.
Syntax
Following is the declaration for strspn() function.
size_t strspn(const char *string1, const char *string2)
- string1 − This is the string to be scanned.
- string2 − This is the string containing the list of characters to match in string1.
Also read about “strcat() function in C, and Tribonacci Series
Code
The following code shows the uses of the strspn() function. We will take two strings, "string1" and "string2," then we will return the length of the starting substring of the string referenced to by string1 that contains just the characters from the string pointed to by string2.
#include <stdio.h>
#include <string.h>
int main () {
char string1[] = "codingninjas";
char string2[] = "code";
int len = strspn(string1,string2);
printf("Length of matching string is : %d\n", len );
return(0);
}
Output
Length of initial segment matching : 3
Note: We initialized the two strings in the above code, but we can also allow the users to give any input of their choice and execute this function on them.
You can also read about the dynamic arrays in c, Short int in C Programming and C Static Function
Must Read Decision Making in C