AppDividend
Latest Code Tutorials

C++ strcspn() Function Example | std::strcspn in C++

0

C++ strcspn() is an inbuilt function that is used for string handling. It is defined in string.h header file. The strcspn() function calculates a 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.

C++ strcspn() Function

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

Syntax

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

Here str_var1 and str_var2 are the string variables that will be 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 a number of 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 character to be scanned, which 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, which consists 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

Your email address will not be published.

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