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
Users Online
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Latest Articles
Articles Hierarchy
C++ Program to Implement strspn() Function
C++ Program to Implement strspn() Function
This is a C++ Program to Implement the strspn() Function.
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.
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.
Here is the source code of C++ Program to Implement the strspn() Function. The program output is shown below.
-
#include<iostream>
-
#include<iostream>
-
#include<string.h>
-
using namespace std;
-
int main ()
-
{
-
char str1[50], str2[50];
-
int i, j, count = 0;
-
cout << "Enter string 1 : ";
-
gets(str1);
-
cout << "Enter string 2 : ";
-
gets(str2);
-
for (i = 0 ; str1[i] != '\0'; i++)
-
{
-
for (j = 0; str2[j] != '\0'; j++)
-
{
-
if (str1[i] == str2[j])
-
count++;
-
}
-
}
-
cout << "Length of string 1 containing '" << str2 << "' characters : " << count;
-
return 0;
-
}
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.