C Reference String Operation: strchr()

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

Usage:

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

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

strchr() source code example:


#include<stdio.h>
#include<string.h>

main()
{
	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");
	else
	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. You can leave a response, or trackback from your own site. 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’

Leave a Reply: