Strcspn() function in C
The length of the characters before the first character contained in both strings is determined using the C library function strcspn().
Parameters or arguments used in this function:
The string that must be searched for, or the target string.
Characters from the argument string are used to match the target string.
This function calculates the number of characters that come before the first character that appears in both strings.
The unmatched characters before first matched character : 1
Another example with detailed explanation:
The length of the initial segment of str1 that does not contain any characters from str2 is: 2
The length of the first segment of a string that doesn't contain any characters from a predetermined set of characters is determined by the strcspn() function.
Two strings are used in this example: str1 and str2. The words "Hello, india" are in str1, while the letters "llo" are in str2. The length of the first part of str1 that doesn't include any characters from str2 is what we're looking for.
The strcspn() function requires two arguments: str1 is the string to search for, and str2 is the collection of characters to look for. The method gives back the length of the first part of str1 that doesn't include any characters from str2. As there are no characters from str2 in the first segment of the string "Hell" in str1, the strcspn() function will return 7 in this case.
After that, the length of the original segment is displayed by printing the outcome using the printf() function. When you need to determine the length of a substring that excludes specific characters, the strcspn() method comes in useful.
This function can be used in a variety of practical contexts, including word games and irregularity calculators. This article demonstrates a straightforward word game.
In this game, two players participate, and the first player is tasked with creating a string with as many unmatched characters as possible. After one round, the person who produced the longest line of mismatched characters won.
Match Drawn!! Score : 1