strcspn() Function

The strcspn() function in C computes the length of the initial segment of a string that does not include any characters from a specified set. It scans the string until a character from that set is encountered, and if none are found, it returns the total length of the string.


Syntax of strcspn()

</>
Copy
size_t strcspn(const char *str1, const char *str2);

Parameters

ParameterDescription
str1C string to be scanned.
str2C string containing the set of characters to match.

Note: The function examines the characters in the string, including the terminating null-character. If no character from the set is encountered, the returned value is equal to the full length of the string.


Examples for strcspn()

Example 1: Basic Usage

This example demonstrates how strcspn() finds the length of the initial segment of a string until a delimiter is encountered.

Program

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

int main() {
    char str1[] = "Hello, World!";
    char str2[] = ",!";
    size_t span = strcspn(str1, str2);
    printf("The span is: %zu\n", span);
    return 0;
}

Output:

The span is: 5

Example 2: No Matching Character

This example shows the scenario when none of the characters from the set are present in the string, resulting in the entire string length being returned.

Program

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

int main() {
    char str1[] = "abcdef";
    char str2[] = "XYZ";
    size_t span = strcspn(str1, str2);
    printf("The span is: %zu\n", span);
    return 0;
}

Output:

The span is: 6

Example 3: Immediate Match

This example demonstrates a case where the first character of the string is immediately found in the set, resulting in a span of zero.

Program

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

int main() {
    char str1[] = "12345";
    char str2[] = "1";
    size_t span = strcspn(str1, str2);
    printf("The span is: %zu\n", span);
    return 0;
}

Output:

The span is: 0