C++ program to locate a character in a string using strpbrk

C++ program to locate a character in a string using strpbrk:

In this post, we will learn how to locate a character in a string using strpbrk function in C++. strpbrk function is defined in cstring header file. So, we need to use c type string for this function, i.e. character array.

This post will show you the definition of this method and how to use it with examples.

Definition of strpbrk:

strpbrk method is defined as like below:

const char * strpbrk ( const char * firstStr, const char * secondStr );

It takes two char * as its arguments. It returns one char * to the first occurrence of a character in firstStr of any of the characters in secondStr. If no matches are found, it returns a null pointer.

Example program of strpbrk:

Let’s take a look at the below program:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char firstStr[] = "Hello world";
    char secondStr[] = "o";

    char *ch = strpbrk(firstStr, secondStr);

    if (ch != NULL)
    {
        printf("Found the character");
    }
    else
    {
        printf("Given character is not in the string");
    }
    return 0;
}

Here,

  • firstStr is the given string.
  • secondStr is a string with one character.
  • strpbrk returns one non-null value if it finds any of secondStr character in firstStr. Based on that, we can say the character is in the string or not.

Check if a string contains any vowel using strpbrk:

We can also use strpbrk to check if a string contains any vowel or not as like below:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char firstStr[] = "Hello world";
    char secondStr[] = "aeiouAEIOU";

    char *ch = strpbrk(firstStr, secondStr);

    if (ch != NULL)
    {
        printf("The given string contains vowel");
    }
    else
    {
        printf("The given string doesn't have any vowel");
    }
    return 0;
}

It will check if any of the uppercase or lowercase vowel is in firstStr or not. Based on the return value of strpbrk, we can say the string firstStr contains vowels or not.

You can try these programs with different string values to check the result.

You might also like: