strchr – Find Character In A String C and C++ Tutorial with Examples – POFTUT

strchr – Find Character In A String C and C++ Tutorial with Examples


C library provides a lot of functions in order to use string or char array types. strchr() function is a very popular function which is used to find the first occurrence of a given character in a string or char array.

Syntax and Parameters

As strchr() provides the first occurrence of the given char it will return a pointer to the first occurrence.  We will also provide the string or char array we are searching in and the chart we want to locate.

char * strchr(const char*, int);
  • `const char*` type is the string or char array we are searching in
  • `int` is the char we are searching for value

Return Value

The return value is a char pointer to the first occurrence of the given char .

Example with C

We will start with a C example where we will search the s character in the string named str.

/* strchr() function C example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "I really like the poftut.com";
  char * pch;
  printf ("Looking for the 'l' character in \"%s\"...\n",str);
  pch=strchr(str,'l');
  while (pch!=NULL)
  {
    printf ("'l' found at %d\n",pch-str+1);
     pch=strchr(pch+1,'s');
  }
  return 0;
}

We will compile with the following gcc command.

$ gcc strchr.c -o strchr_C_example

and call the example executable strchr_C_example.

$ ./strchr_C_example
Example with C
Example with C

Example with C++

As stated previously strchr() function exist in C++ programming language standard library. It has the same syntax where provided by std library as a static function.

//strchr() function C++ examples

#include <iostream>
#include <cstring>

int main()
{
  const char *str = "I really like poftut.com";
  char target = 'l';
  const char *result = str;

  while ((result = std::strchr(result, target)) != NULL) {
    std::cout << "'l' found '" << target
    << "' starting at '" << result << "'\n";

    ++result;
  }
}

We will compile an example with the following g++ command.

$ g++ strchr_Cpp_example.cpp -o strchr_Cpp_example

and then we will call created example binary strchr_Cpp_example

$ ./strchr_Cpp_example
Example with C++
Example with C++

LEARN MORE  Python Variables and Types

1 thought on “strchr – Find Character In A String C and C++ Tutorial with Examples”

Leave a Comment