C - String Searching for a Character

Introduction

The strchr() function searches a given string for a specified character.

The first argument is the string to be searched, and the second argument is the character that you're looking for.

The function will search the string starting at the beginning and return a pointer to the first position where the character is found.

The returned value is the address of this position in memory and is of type char*.

If the character isn't found, the function returns a special value NULL.

char str[] = "this is a test test test";    // The string to be searched
char ch = 's';                         // The character we are looking for
char *pGot_char = NULL;                // Pointer initialized to NULL
pGot_char = strchr(str, ch);           // Stores address where ch is found

The first argument to strchr() is the address of the first location to be searched.

The second argument is the character that is sought, which is of type char.

The strchr() function expects the second argument to be of type int.

You could just as well define ch as type int like this:

int ch = 'q';                          // Initialize with character code for q

You can search for multiple occurrences of a character quite easily using:

char str[] = "this is a test test test test test test.";    // The string to be searched
char ch = 's';                             // The character to look for
char *pGot_char = str;                     // Pointer initialized to string start
int count = 0;                             // Number of times found
while(pGot_char = strchr(pGot_char, ch))   // As long as NULL is not returned...
{                                          
  ++count;                                 // Increment the count
  ++pGot_char;                             // Move to next character address
}
printf("The character '%c' was found %d times in the following string:\n\"%s\"\n",
                                                                  ch, count, str);