Skip to main content

Command Palette

Search for a command to run...

Searching for a character within a string

Published
•2 min read•View as Markdown

The function strchr() searches the occurrence of a specified character in the given string and returns the pointer to it.

C strchr() Function

char *strchr(const char *str, int ch)

str – The string in which the character is searched.
ch – The character that is searched in the string str.

Return Value of strchr()

It returns the pointer to the first occurrence of the character in the given string, which means that if we display the string value of the pointer then it should display the part of the input string starting from the first occurrence of the specified character.

A variant strrchr

It returns the pointer to the last occurrence of the character in the given string.

Example: strchr() function in C

In this example, we have a string and we are searching a character ‘u’ in the string using strchr() and strrchr() functions. When we displayed the string value of the returned pointer of the function, it displayed the string starting from the character ‘u’, this is because the pointer returned by the function points to the character ‘u’ in the string.

Program:

#include <stdio.h>
#include <string.h>
int main () {
   const char str[] = "This is just a String";
   const char ch = 'u';
   char *p;
   p = strchr(str, ch);
   printf("Character %c first found at index: %d\n", ch, p-str);
   printf("String starting from %c is: %s\n", ch, p);
   return 0;
}

Output:

To find the index, here we have done pointer subtraction, subtracting the pointer to the first element from the pointer returned by strchr() and strrchr().

25 views

More from this blog

P

Programming Tutorials

89 posts