
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C library - strspn() function
The C library strspn() function is used to find the length of prefix(str1) that contains only characters present in another string(str2).
It allows for easy customization by accepting any two strings as input. Thus, this enable the comparison of different characters set and strings.
Syntax
Following is the syntax of the C library strsmp() function −
size_t strspn(const char *str1, const char *str2)
Parameters
This function accepts the following parameters −
str1 − This is the main C string to be scanned.
str2 − This is the string containing the list of characters to match in str1.
Return Value
This function returns the number of characters in the initial segment of str1 that consist only of characters from str2.
Example 1
We use the C library function strspn() that demonstrates the comparison of two prefix substring from the given string and find its length.
#include <stdio.h> #include <string.h> int main () { int len; const char str1[] = "ABCDEFG019874"; const char str2[] = "ABCD"; len = strspn(str1, str2); printf("Length of initial segment matching %d\n", len ); return(0); }
Output
The above code produces the following result −
Length of initial segment matching 4
Example 2
Following the C program uses the function strsmp() to filter the non-alphabetical letters from the given string.
#include <stdio.h> #include <string.h> const char* low_letter = "qwertyuiopasdfghjklzxcvbnm"; int main() { char s[] = "tpsde312!#$"; size_t res = strspn(s, low_letter); printf("After skipping initial lowercase letters from '%s'\nThe remainder becomes '%s'\n", s, s + res); return 0; }
Output
After execution of code, we get the following result −
After skipping initial lowercase letters from 'tpsde312!#$' The remainder becomes '312!#$'
Example 3
Below the program illustrate the strspn() to find the length of prefix substring from the main string.
#include <stdio.h> #include <string.h> int main () { int leng = strspn("We are Vertos", "We"); printf("Length of initial characters matching : %d\n", leng ); return 0; }
Output
On execution of above code, we get the following result −
Length of initial characters matching : 2