strcspn() function in C++

In this guide, you will learn what is strcspn() function is in C++ programming and how to use it with an example.

1. strcspn() Function Overview

The strcspn() function, part of the <cstring> library in C++, computes the length of the initial segment of the first given string (str1) that consists entirely of characters not present in the second given string (str2).

Signature:

size_t strcspn(const char* str1, const char* str2);

Parameters:

- str1: The main string where the search is performed.

- str2: The string containing characters to be searched for in str1.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    const char* string = "123abcDEF";
    const char* chars_to_find = "abc";

    size_t length = strcspn(string, chars_to_find);

    std::cout << "Length of the initial segment of 'string' without any characters from 'chars_to_find' is: " << length << std::endl;

    return 0;
}

Output:

Length of the initial segment of 'string' without any characters from 'chars_to_find' is: 3

3. Explanation

1. We've included the <iostream> header for standard input/output and <cstring> for the strcspn() function.

2. We initialize two strings: string and chars_to_find. We aim to determine the length of the initial segment of string that doesn't have any characters present in chars_to_find.

3. We then use the strcspn() function to find the length of that segment.

4. The result is displayed.

Note: The distinction between strspn() and strcspn() is critical. While strspn() searches for the segment containing only the specified characters, strcspn() searches for the segment not containing any of the specified characters. This function is particularly useful in various parsing scenarios.


Comments