strspn Function

Calculate the number of consecutive characters at the beginning of a string that are contained in a set of characters.

Include

<string.h>

Prototype

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

Arguments

s1
pointer to the string to be searched
s2
pointer to characters to search for

Return Value

Returns the number of consecutive characters from the beginning of s1 that are contained in s2.

Remarks

This function stops searching when a character from s1 is not in s2.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int main(void)
{
  char str1[20] = "animal";
  char str2[20] = "aeiounm";
  char str3[20] = "aimnl";
  char str4[20] = "xyz";
  int res;

  res = strspn(str1, str2);
  printf("strspn(\"%s\", \"%s\") = %d\n", 
          str1, str2, res);

  res = strspn(str1, str3);
  printf("strspn(\"%s\", \"%s\") = %d\n", 
          str1, str3, res);

  res = strspn(str1, str4);
  printf("strspn(\"%s\", \"%s\") = %d\n", 
          str1, str4, res);
}

Example Output

strspn("animal", "aeiounm") = 5
strspn("animal", "aimnl") = 6
strspn("animal", "xyz") = 0

Example Explanation

In the first result, l is not in s2.

In the second result, the terminating null is not in s2.

In the third result, a is not in s2 , so the comparison stops.