strcspn is a function in the C standard library used to find the length of the initial segment of a string that does not contain any of the specified characters.

strcspn Function Header File

The header file for the strcspn function is <string.h>. Before using the strcspn function, make sure to include this header file in your C code:

#include <string.h>

strcspn Function Prototype

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

The strcspn function calculates the length of the longest initial segment of the string pointed to by s1, consisting of characters that are not in the string pointed to by s2.

Parameter Description

  • s1: A pointer to the string to be searched
  • s2: A string containing the characters to be excluded;

Return Value

The strcspn function returns the length of the initial segment; if no characters from s2 are found in s1, it returns the length of s1;

strcspn Example Code

#include <stdio.h>
#include <string.h>

int main() {

    const char* str1 = "Hello, world";
    const char* str2 = "?Hello, world";
    const char* str3 = "helloworld";

    const char* chars = " ,?";

    size_t result1 = strcspn(str1, chars);
    size_t result2 = strcspn(str2, chars);
    size_t result3 = strcspn(str3, chars);

    printf("%ld\n%ld\n%ld\n", result1,result2,result3);

    return 0;
}

Program Output

5
0
10