C Programming: strpbrk() Function

beginner
10 min

C Programming: strpbrk() Function

Welcome, programmer! Today, we're diving into the fascinating world of C programming and learning about the strpbrk() function. This function is a powerful tool that helps you find specific characters or strings within a given string. Let's get started!

Introduction 🎯

Before we dive into the strpbrk() function, let's quickly review some basics:

  • Strings: In C, a string is an array of characters terminated by a null character (\0).
  • Arrays: A collection of elements of the same data type.

What is strpbrk()? 📝

The strpbrk() function checks a given string for any of a set of specified characters and returns a pointer to the matched character if found. If no matching character is found, it returns a null pointer (NULL).

Syntax 💡

c
char *strpbrk(const char *s1, const char *s2);
  • s1: The string to be searched.
  • s2: The set of characters to search for in s1.

Example ✅

Let's consider a simple example:

c
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello, World!"; char *result = strpbrk(str1, "oWl"); if (result != NULL) { printf("Found character: %c\n", *result); } else { printf("No matching character found.\n"); } return 0; }

In this example, we're searching the string "Hello, World!" for the characters 'o', 'W', and 'l'. The strpbrk() function finds the 'o' and returns a pointer to it. The output will be:

Found character: o

Advance Example 💡

Let's consider a more complex example:

c
#include <stdio.h> #include <string.h> int main() { char str1[] = "Here is a sample string for strpbrk() function."; char *searchChars = ",.!? "; char *result = strpbrk(str1, searchChars); if (result != NULL) { printf("Found character: %c\n", *result); } else { printf("No punctuation marks found.\n"); } return 0; }

In this example, we're searching the string "Here is a sample string for strpbrk() function." for punctuation marks (, . ! ?). The strpbrk() function finds the comma (,) and returns a pointer to it. The output will be:

Found character: ,

Quiz 💡

Quick Quiz
Question 1 of 1

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

With this, you've learned the basics of the strpbrk() function in C programming. As you practice more, you'll find it to be a very useful tool in your programming arsenal. Happy coding! 🎉