AppDividend
Latest Code Tutorials

C++ strspn() Function Example | std::strspn In C++

0

C++ strspn() is an inbuilt string handling function that works with two parameters and returns the length of the initial substring of the string which is pointed by the first parameter(string1) which only consists of the characters that are present in the string which is pointed by the second parameter(string2). It is defined as a string.h header file.

C++ strspn()

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

Syntax

size_t strspn( const char* destination_var, const char* source_var)

Parameters

It takes two parameters. The first one is destination_var which is a pointer that points to the string which is to be scanned. The second one is the source_var which is a pointer that points to the string that contains the character which is to be matched.

Return Value

It returns the number of characters in the initial substring first parameter which consists of the character from the second parameter.

Example programs on strspn() in C++

Write a program in C++ to show the mechanism of strspn().

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

int main()
{
  int k, l, m, n;
  k = strspn("Lionel Messi is the best", "Lionel");
  cout << " Length of the Substring present: " << k << endl;
  l = strspn("I love iron man", "spiderman");
  cout << " Length of the Substring present: " << l;
}

Output

Length of the Substring present: 6
Length of the Substring present: 0

Write a program to use strspn() forming the initial substring of integers in C++

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

int main()
{
  int k;
  char q[] = "998877";
  char a[] = "abcdef998877ghijk";
  k = strspn(q, a);
  cout << "Substring: " << q << "\n"
       << "Substring present: " << k << endl;
}

Output

Substring: 998877
Substring present: 6

See also

C++ strpbrk()

C++ strcspn()

C++ strcncmp()

C++ strcmp()

C++ strchr()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.