In this guide, you will learn what is strspn() function is in C++ programming and how to use it with an example.
1. strspn() Function Overview
The strspn() function, which is part of the <cstring> library in C++, determines the length of the initial segment of the first given string that consists entirely of characters present in the second given string.
Signature:
size_t strspn(const char* str1, const char* str2);
Parameters:
- str1: The main string in which the search is performed.
- str2: The string containing characters to be matched against str1.
2. Source Code Example
#include <iostream>
#include <cstring>
int main() {
const char* string = "123abcDEF";
const char* match_chars = "1234567890";
size_t length = strspn(string, match_chars);
std::cout << "Length of the initial segment of 'string' containing only characters from 'match_chars' is: " << length << std::endl;
return 0;
}
Output:
Length of the initial segment of 'string' containing only characters from 'match_chars' is: 3
3. Explanation
1. The <iostream> header is included for standard input/output and <cstring> for the strspn() function.
2. Two strings are initialized: string and match_chars. We aim to determine the length of the initial segment of string that contains only characters present in match_chars.
3. The strspn() function is used to find the length of the said segment.
4. The result is then displayed.
The strspn() function is especially helpful when trying to analyze a string's composition based on specific characters or class of characters, like determining the length of the numeric prefix of a string.
Comments
Post a Comment