Strcspn() function in C
×


Strcspn() function in C

80

The strcspn function in C is used to find the length of the initial segment of a string that does not contain any characters from a specified set.

It is declared in the <string.h> header file.

The strcspn function scans the string pointed to by the first parameter (s1) until it finds any character that matches one of the characters in the string pointed to by the second parameter (s2).

It returns the length of the initial segment of s1 that does not contain any of the characters in s2.

Syntax strcspn function in C:

size_t strcspn(const char *s1, const char *s2);

s1: Pointer to the null-terminated string to be scanned.

s2: Pointer to the null-terminated string containing the characters to match.


Example:

Program 1:

//program for strcspn function in C
#include<stdio.h>
#include<string.h> 

int main() {
    char str[] = "hello world";
    char charset[] = "aeiou";

    size_t length = strcspn(str, charset);
    
    printf("Length of initial vowels: %zu\n", length);

    return 0;
}	

Output:

Length of initial vowels: 1

We import the required header files stdio.h and string.h.

We initialize a character array str with the string "hello world".

Additionally, we define another character array charset comprising the vowels 'a', 'e', 'i', 'o', and 'u'.

We use the strcspn function to find the length of the initial segment of str that does not contain any vowels.

The result is printed using printf.


Program 2:

//Program for strcspn function in C
#include<stdio.h> 
#include<string.h> 

int main() {
    char str[] = "programming";
    char charset[] = "abcdefghijklmnopqrstuvwxyz";

    size_t length = strcspn(str, charset);
    
    printf("Length of initial segment without characters: %zu\n", length);

    return 0;
}	

Output:

Length of initial segment without characters: 0

Similar to Program 1, we include the necessary header files and declare the required variables.

In this program, we're finding the length of the initial segment of str that does not contain any alphabet characters.

We use the strcspn function to achieve this.

Finally, we print the result using printf.

These programs demonstrate the usage of the strcspn function to find the length of initial segments of strings without specific characters or character sets.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments