The strchr and strrchr functions ﬁnd a character in a string, that is in a NUL-terminated character array. strchr return a pointer to the ﬁrst occurrence and strrchr to the last one.
char toSearchFor = 'A';
/* Exit if no second argument is found. */
if (argc != 2)
char *firstOcc = strchr(argv, toSearchFor);
if (firstOcc != NULL)
printf("First position of %c in %s is %td.\n", toSearchFor, argv, firstOcc-argv);
/* A pointer difference's result is a signed integer and uses the length modifier 't'. */
printf("%c is not in %s.\n", toSearchFor, argv);
char *lastOcc = strrchr(argv, toSearchFor);
if (lastOcc != NULL)
printf("Last position of %c in %s is %td.\n",
toSearchFor, argv, lastOcc-argv);
Outputs (after having generate an executable named pos):
$ ./pos AAAAAAA
First position of A in AAAAAAA is 0.
Last position of A in AAAAAAA is 6.
$ ./pos BAbbbbbAccccAAAAzzz
First position of A in BAbbbbbAccccAAAAzzz is 1.
Last position of A in BAbbbbbAccccAAAAzzz is 15.
$ ./pos qwerty A is not in qwerty.
One common use for strrchr is to extract a ﬁle name from a path. For example to extract myfile.txt from C:\Users\eak\myfile.txt:
char *getFileName(const char *path)
if ((pend = strrchr(path, '\')) != NULL)
return pend + 1;