C++ strcspn() Function: Guide on std::strcspn

0
3
C++ strcspn() Function Example | std strcspn in C++

The strcspn() function in C++ takes two null-terminated byte strings: dest and src as its argument and searches dest for any characters present in src.

C++ strcspn()

C++ strcspn() is a built-in function that is used for string handling. It is defined in string.h header file. The strcspn() function calculates the length of the characters before the first occurrence of that particular character in both the strings. In simpler words, it searches for the characters of one string in another string.

Syntax

size_t strcspn(const char *str_var1, const char *str_var2);

Here str_var1 and str_var2 are the string variables used for all the operations using this function.

Parameters

The C++ strcspn() function takes two parameters str_var1 and str_var2. Here the function searches for the str_var1 for any characters that are present in str_var2.

Return Value

The strcspn() function returns several characters before the occurrence of a particular specified character in both the strings.

Example programs on strcspn() in C++

Example 1: Write a program to show the working of strcspn() in C++

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

using namespace std;

int main()
{
  char k[] = "qwerty";
  char f[] = "rt";
  int len;
  len = strcspn(k, f);
  cout << "Length of character before occurance of the second string: " << len;
  return 0;
}

Output

Length of character before the occurrence of the second string: 3

Example 2: Write a program to pass characters to be scanned, which is not present and hence show the output.

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

using namespace std;

int main()
{
  char k[] = "Messi";
  char f[] = "ro";
  int len;
  len = strcspn(k, f);
  cout << len;

  cout << "Sorry nothing matches in the above string, so the unmatched length:  " << len << endl;

  return 0;
}

Output

Sorry nothing matches in the above string, so the unmatched length:  5	

Returns a length of the maximum initial segment of the byte string pointed to by k, consisting of only the characters not found in a byte string pointed to by f.

In the above code, the char f = “ro” is not included in “Messi“, so it will return. Sorry, nothing matches in the above string, so the unmatched length.

Conclusion

The C++ strcspn(const char *str1, const char *str2) calculates a length of the initial segment of str1, which consists wholly of characters, not in str2.

See also

C++ strcncmp()

C++ strcmp()

C++ strchr()

C++ memchr()

Leave A Reply

Please enter your comment!
Please enter your name here

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