strstr() / strchr() / strrchr()
Functions that search for a specific substring or character within a string. Commonly used in parsers, log analysis, and other tasks where you need to extract information from a string.
Syntax
// Searches for needle within haystack. // Returns: a pointer to the first occurrence, or NULL if not found. char *strstr(const char *haystack, const char *needle); // Searches for character c in string s from the beginning. // Returns: a pointer to the first occurrence, or NULL if not found. char *strchr(const char *s, int c); // Searches for character c in string s from the end (finds the last occurrence). char *strrchr(const char *s, int c); // Returns a pointer to the first character in s that matches any character in accept. char *strpbrk(const char *s, const char *accept);
Function List
| Function | Search target | Direction | Description |
|---|---|---|---|
| strstr() | Substring | Forward | Returns a pointer to needle if it exists within haystack. |
| strchr() | Single character | Forward | Returns the position of the first occurrence of the character. Can also search for the null character ('\0'). |
| strrchr() | Single character | Backward | Returns the position of the last occurrence of the character. Often used to extract a file extension from a path. |
| strpbrk() | Character set | Forward | Returns the position of the first character in s that matches any character in accept. |
Sample Code
#include <stdio.h>
#include <string.h>
int main(void) {
const char *path = "/home/user/documents/report.txt";
// Use strstr to check whether the path contains "documents".
if (strstr(path, "documents")) {
printf("The file is inside the documents folder.\n");
}
// Use strchr to find the position of the first '/'.
char *first_slash = strchr(path, '/');
printf("From the first '/': %s\n", first_slash); // "/home/user/documents/report.txt"
// Use strrchr to extract the file extension from the path.
char *ext = strrchr(path, '.');
if (ext) {
printf("Extension: %s\n", ext); // ".txt"
}
// Use strrchr to extract the filename from the path.
char *filename = strrchr(path, '/');
if (filename) {
printf("Filename: %s\n", filename + 1); // "report.txt"
}
// Use strpbrk to find the position of a delimiter (comma or space).
const char *csv = "apple,banana orange";
char *sep = strpbrk(csv, ", ");
if (sep) {
printf("First delimiter: '%c'\n", *sep); // ','
}
return 0;
}
Notes
These functions return a pointer to the found position, which lets you continue processing from the middle of the original string. Always check whether the return value is NULL before using it. Dereferencing a NULL pointer causes undefined behavior.
You can calculate a zero-based index by subtracting the start address of the string from the found position (e.g., pos - haystack).
For string copying and concatenation, see strlen() / strcpy() and strcat().
If you find any errors or copyright issues, please contact us.