Javatpoint Logo
Javatpoint Logo

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().

Syntax:

Parameters or arguments used in this function:

str1:

The string that must be searched for, or the target string.

str2:

Characters from the argument string are used to match the target string.

Value Returned:

This function calculates the number of characters that come before the first character that appears in both strings.

Example:

Output:

The unmatched characters before first matched character : 1

Another example with detailed explanation:

Output:

The length of the initial segment of str1 that does not contain any characters from str2 is: 2

Explanation:

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.

Relevant Application:

This function can be used in a variety of practical contexts, including word games and irregularity calculators. This article demonstrates a straightforward word game.

Rules:

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.

Output:

Match Drawn!! Score : 1

Next TopicStrftime() in C





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA