C++ strspn()

The strspn() function in C++ takes two string dest and src and gives the length of maximum initial segment of the string dest that consists of characters that are present in the string src.

strspn() prototype

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

It is defined in <cstring> header file.

strspn() Parameters

  • dest: Pointer to the null terminated byte string to be searched for.
  • src: Pointer to the null terminated byte string that contains the characters to search for.

strspn() Return value

The strspn() function returns the length of the maximum initial segment of dest that contains only characters from byte string pointed to by src.

Example: How strspn() function works

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char src[] = "0123456789";
    char dest[] = "190126abqs121kfew";
    
    size_t length = strspn(dest, src);

    cout << dest << " contains " << length << " initial numbers";
    return 0;
}

When you run the program, the output will be:

190126abqs121kfew contains 6 initial numbers