strspn() —Find Offset of First Non-matching Character

Format

#include <string.h>
size_t strspn(const char *string1, const char *string2);

Language Level: ANSI

Threadsafe: Yes.

Locale Sensitive: The behavior of this function might be affected by the LC_CTYPE category of the current locale. For more information, see Understanding CCSIDs and Locales.

Description

The strspn() function finds the first occurrence of a character in string1 that is not contained in the set of characters that is specified by string2. The null character (\0) that ends string2 is not considered in the matching process.

Return Value

The strspn() function returns the index of the first character found. This value is equal to the length of the initial substring of string1 that consists entirely of characters from string2. If string1 begins with a character not in string2, the strspn() function returns 0. If all the characters in string1 are found in string2, the length of string1 is returned.

Example that uses strspn()

This example finds the first occurrence in the array string of a character that is not an a, b, or c. Because the string in this example is cabbage, the strspn() function returns 5, the length of the segment of cabbage before a character that is not an a, b, or c.

#include <stdio.h>
#include <string.h>
 
int main(void)
{
  char * string = "cabbage";
  char * source = "abc";
  int index;
 
  index = strspn( string, "abc" );
  printf( "The first %d characters of \"%s\" are found in \"%s\"\n",
          index, string, source );
}
 
/*****************  Output should be similar to:  *****************
 
The first 5 characters of "cabbage" are found in "abc"
*/

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]