Library contents

C strchr

Search a null-terminated byte string for a separator and use the returned pointer to locate it.

A simple example

strchr

  1. Start with "aba", looking for b
  2. Do this Find the first match
  3. Result Index 1 (zero-based)
Scanning from the left reaches b after one character.

Syntax

C 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
./lesson

Locate 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.

From the programconst char *tag = "AB-C-D"
Result2
lesson.c
#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;
}
Output
2

Subtract two pointers into the same array to obtain the zero-based byte offset.

Advertisements

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.

From the programconst char *tag = "PAID"
ResultNo divider
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *tag = "PAID";
    puts(strchr(tag, '-') == NULL ? "No divider" : "Found");
    return 0;
}
Output
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?

GivenNC-17
Worked result2

What to watch for

Check for a null pointer before calculating its offset. A byte position need not be a Unicode character position.

Documentation for strchr