Users Online

· Guests Online: 114

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C++ Program to Implement strspn() Function

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.

 
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

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.15 seconds
10,266,223 unique visits