w3resource

C - strcspn() function

C strcspn() function - get the length of a complementary substring

Syntax:

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

The strcspn() function is used to find the first occurrence of a character in s1 that belongs to the set of characters that is specified by s2.

Parameters:

Name Description Required /Optional
s1 Null-terminated searched string. Required
s2 Null-terminated character set. Required

Return value from strcspn()

  • The strcspn() function returns the index of the first character found.
  • Return the length of the string if no match found.
  • No return value is reserved to indicate an error.

Example: strcspn() function

This example uses strcspn() to find the first occurrence of some characters in a string.


#include <stdio.h>
#include <string.h>
 
#define SIZE 40
 
int main(void)
{
  char string1[SIZE] = "C Language";
  char ch;
  int index;
  printf("Original string: %s", string1);
  index = strcspn(string1, "C");
  printf("\n\nIndex of character 'C' in the said string is %d.",index);
  index = strcspn(string1, "L");
  printf("\n\nIndex of character 'L' in the said string is %d.",index);
  index = strcspn(string1, "a");
  printf("\n\nIndex of character 'a' in the said string is %d.",index);
  index = strcspn(string1, "g");
  printf("\n\nIndex of character 'g' in the said string is %d.",index);
  index = strcspn(string1, "U");
  printf("\n\nIndex of character 'U' in the said string is %d.",index);
}

Output:

Original string: C Language

Index of character 'C' in the said string is 0.

Index of character 'L' in the said string is 2.

Index of character 'a' in the said string is 3.

Index of character 'g' in the said string is 5.

Index of character 'U' in the said string is 10.

C Programming Code Editor:

Previous C Programming: C strncpy()
Next C Programming: C strerror()



Follow us on Facebook and Twitter for latest update.