C Reference String Operation: strchr()

The function strchr() returns a pointer to the first occurrence of x in a string.


char *strchr( const *str, int x);

Note: NULL will be returned if x isn’t found.

strchr() source code example:


	char line[100];
	char *ptr_my;

	printf("Input word:");
	scanf("%s", line);

	ptr_my=strchr(line, 'a');

	if (ptr_my == NULL)
		printf("Character a is not found.\n");
	printf("Character found at position %d\n", ptr_my - line+1);

Output of the example:

	Input word:testen
	Character a is not found.

	Input word:tastan
	Character found at position 2

Note: the program was executed two times to get the result of the output example.

This entry was posted in C Reference string.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There is currently one response to “C Reference String Operation: strchr()”

Why not let us know what you think by adding your own comment!

  1. Greg on September 19th, 2011:

    The function main() should either be type void or int and a return value. So I added:
    int main ()

    return 0;
    I’m on Ubuntu natty, with AMD64 cpu, when compiling with: gcc -Wall -o string1 string1.c
    I get:
    string1.c: In function ‘main’:
    string1.c:25:2: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long int’