C++ Program to Implement strspn() Function

This is a C++ Program to Implement the strspn() Function.

Problem Description

The program implements the function strspn() which takes two strings and returns the length of portion of first string consisting of characters only from second string.

Problem Solution

1. The program takes two strings.
2. Using for loops, both strings are compared.
3. If characters match, then a variable is incremented.
4. The variable is printed which is the length of the string containing characters common to the entered strings.
5. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Implement the strspn() Function. The program output is shown below.

  1. #include<iostream>
  2. #include<iostream>
  3. #include<string.h>
  4. using namespace std;
  5. int main ()
  6. {
  7.     char str1[50], str2[50];
  8.     int i, j, count = 0;
  9.     cout << "Enter string 1 : ";
  10.     gets(str1);
  11.     cout << "Enter string 2 : ";
  12.     gets(str2);
  13.     for (i = 0 ; str1[i] != '\0'; i++)
  14.     {
  15.         for (j = 0; str2[j] != '\0'; j++)
  16.         {
  17.             if (str1[i] == str2[j])
  18.                 count++;
  19.         }
  20.     }   
  21.     cout << "Length of string 1 containing '" << str2 << "' characters : " << count;
  22.     return 0;
  23. }
Program Explanation

1. The user is asked to enter two strings and stored in ‘str1’ and ‘str2’. A variable ‘count’ is initialized as 0.
2. Using for loops, both strings are compared for same characters.
3. If the condition is true, then count is incremented.
4. The loop terminates when null character is encountered.
5. count is then printed which is the length of the string containing characters which belong to both the strings.

advertisement
Runtime Test Cases
Case 1 :
Enter string 1 : debug
Enter string 2 : debuGGER
Length of string 1 containing 'debuGGER' characters : 4
 
Case 2 :
Enter string 1 : flat
Enter string 2 : 123
Length of string 1 containing '123' characters : 0
 
Case 3 :
Enter string 1 : 2061208
Enter string 2 : 0123456789
Length of string 1 containing '0123456789' characters : 7

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

🎓 Register Today for Free C++ Certification - June 2026

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels
advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations