C++ strcspn()

The strcspn() function in C++ takes two null terminated byte string: dest and src as its argument and searches dest for any characters that is present in src.

strcspn() prototype

size_t strcspn( const char *dest, const char *src );

If either src or dest does not point to a null terminated byte string, the behaviour of strcspn() function is undefined.

It is defined in <cstring> header file.

strcspn() Parameters

  • dest: Pointer to a null terminated string to be searched.
  • src: Pointer to a null terminated string containing the characters to search for.

strcspn() Return value

The strcspn() function returns number of characters in dest before the first occurrence of any characters present in src.

Example: How strcspn() function works

#include <cstring>
#include <iostream>

using namespace std;

int main()
    char num[] = "0123456789";
    char code[] = "ceQasieoLPqa4xz10Iyq";

    size_t result = strcspn(code, num);

    if (result < strlen(code))
        cout << "First occurrence of number in " << code << " is at position " << result;
        cout << code << " does not contain numbers";

    return 0;

When you run the program, the output will be:

First occurrence of number in ceQasieoLPqa4xz10Iyq is at position 12
Did you find this article helpful?