C strchr
Search a null-terminated byte string for a separator and use the returned pointer to locate it.
A simple example
strchr
- Start with "aba", looking for b
- Do this Find the first match
- Result Index 1 (zero-based)
Syntax
strchr(tag, '-')
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonLocate a divider in a shelf code
A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *tag = "AB-C-D";
const char *match = strchr(tag, '-');
if (match != NULL) printf("%td\n", match - tag);
return 0;
}
2
Subtract two pointers into the same array to obtain the zero-based byte offset.
Handle a receipt with no divider
A receipt import usually finds a divider between two fields, but a shortened record has none. Check the search result before using it as a position for a second operation.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *tag = "PAID";
puts(strchr(tag, '-') == NULL ? "No divider" : "Found");
return 0;
}
No divider
A failed search returns a null pointer. Check it before subtraction.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?
What to watch for
Check for a null pointer before calculating its offset. A byte position need not be a Unicode character position.