C Programming: Understanding the `strspn()` Function 🎯

beginner
25 min

C Programming: Understanding the strspn() Function 🎯

Welcome to another enlightening lesson on C Programming at CodeYourCraft! Today, we're diving deep into the strspn() function, a powerful tool for finding the length of a substring in a given string. Let's get started!

What is strspn() Function? 📝

In C programming, the strspn() function calculates the length of the initial segment in s1 of characters common to both s1 and s2.

Syntax 📝

The syntax for the strspn() function is as follows:

c
size_t strspn(const char *s1, const char *s2);

Here, s1 is the string in which the search is made, and s2 is the set of characters that the search string is compared with.

Practical Example 💡

Let's take an example to understand this better.

c
#include <stdio.h> #include <string.h> int main() { char str1[50] = "Welcome to CodeYourCraft!"; char str2[10] = "Craft"; int len = strspn(str1, str2); printf("The length of the substring 'Craft' in the string 'Welcome to CodeYourCraft!' is: %d\n", len); return 0; }

Upon execution, this code will output:

The length of the substring 'Craft' in the string 'Welcome to CodeYourCraft!' is: 5

Key Points 💡

  • strspn() searches for characters in s1 that also appear in s2 and stops as soon as it encounters a character not present in s2.
  • The function returns the length of the initial segment of s1 that consists entirely of characters from s2.
  • If no such characters are found, it returns 0.

Quiz 📝

Quick Quiz
Question 1 of 1

What does the `strspn()` function do in C programming?

Stay tuned for the next lesson, where we'll explore even more C programming concepts to help you master this powerful language! 🚀