strspn() Function

The strspn() function in C computes the length of the initial segment of a string that consists entirely of characters from a specified set. It is commonly used for parsing and validating input where only certain characters are allowed at the beginning of a string.


Syntax of strspn()

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

Parameters

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

Return Value

The function returns the length of the initial segment of str1 that is made up entirely of characters found in str2. If the first character of str1 is not in str2, it returns 0, and if every character in str1 is in str2, it returns the total length of str1.

Note that the scanning stops when a null-character is encountered in either string, ensuring only valid characters are evaluated.


Examples for strspn()

Example 1: Matching Numeric Characters

This example demonstrates how strspn() determines the length of the initial segment of a string that contains only numeric characters.

Program

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

int main() {
    char str[] = "12345abcde";
    size_t len = strspn(str, "0123456789");
    printf("Initial segment length: %zu\n", len);
    return 0;
}

Explanation:

  1. The string "12345abcde" is scanned from the beginning.
  2. The function counts the consecutive characters that are digits.
  3. The scanning stops at the first non-digit character, resulting in a length of 5.

Output:

Initial segment length: 5

Example 2: No Matching Characters

This example shows the scenario where the first character of the string is not part of the specified set, leading to a return value of zero.

Program

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

int main() {
    char str[] = "abcdef12345";
    size_t len = strspn(str, "0123456789");
    printf("Initial segment length: %zu\n", len);
    return 0;
}

Explanation:

  1. The string "abcdef12345" is scanned from the beginning.
  2. Since the first character is not a digit, the function immediately returns 0.

Output:

Initial segment length: 0

Example 3: Full String Match

This example demonstrates a situation where every character in the string is part of the specified set, so the function returns the full length of the string.

Program

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

int main() {
    char str[] = "abcdef";
    size_t len = strspn(str, "abcdef");
    printf("Initial segment length: %zu\n", len);
    return 0;
}

Explanation:

  1. The string "abcdef" is entirely composed of characters from the matching set.
  2. The function scans the complete string and returns a length of 6.

Output:

Initial segment length: 6