Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

C++ cstring strspn() Function



The C++ strspn() function is used to find the length of the initial segment of a string which consists of only the characters that are present in another string.

This function is similar to the strcspn() function but the difference is that strcspn() function finds the length of the initial segment of a string which consists of only the characters that are not present in another string.

Syntax

Following is the syntax of the strspn() function −

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

Parameters

Parameters of the strspn() function are as follows −

  • str1: This is the string to be checked.
  • str2: This is the string containing the characters to match.

Return Value

The strspn() function returns the length of the initial segment of str1 that consists of only the characters found in str2.

Example 1

In the following example, we will take two strings str1 and str2 and then find the length of the initial segment of str1 that consists of only the characters found in str2 using the strspn() function.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
   char str1[] = "tutorialspoint";
   char str2[] = "aeiou";
   size_t ret;

   ret = strspn(str1, str2);

   cout << "Length of the initial segment of str1 that consists of only the characters found in str2: " << ret << endl;

   return 0;
}

Output

Following is the output of the above C++ program −

Length of the initial segment of str1 that consists of only the characters found in str2: 3

Example 2

Now, let's check a case where the initial segment of str1 contains all the characters found in str2.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
   char str1[] = "tutorialspoint";
   char str2[] = "tutor";
   size_t ret;

   ret = strspn(str1, str2);

   cout << "Length of the initial segment of str1 that consists of only the characters found in str2: " << ret << endl;

   return 0;
}

Output

Following is the output of the above C++ program −

Length of the initial segment of str1 that consists of only the characters found in str2: 5
Advertisements