C++ Standard Library C++ STL Library

C++ <cstring> - strcspn() Function



The C++ <cstring> strspn() function returns the length of maximum initial segment (span) of the byte string pointed to by str1 which consists of only the characters not present in the byte string pointed to by str2.

The search includes the terminating null-characters and hence returns the length of str1 when none of the characters of str2 are found in str1.

Syntax

size_t strcspn ( const char * str1, const char * str2 );               

Parameters

str1 Specify pointer to the null-terminated byte string to be scanned.
str2 Specify pointer to the null-terminated byte string containing the characters to match.

Return Value

Returns the length of the initial part of str1 not containing any of the characters present in str2. Returns the length of str1 when none of the characters of str2 are found in str1.

Example:

The example below shows the usage of strcspn() function.

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
  char str1[100] = "12345@ABWzx3423S#";
  char str2[100] = "#@,";
  
  //finding the length of maximum initial length of
  //str1 not containing any characters of str2
  int max_initial_len = strcspn(str1, str2);

  //displaying the result
  cout<<"Length of maximum initial length: "
        <<max_initial_len;
 
  return 0;
}

The output of the above code will be:

Length of maximum initial length: 5

❮ C++ <cstring> Library