Lesson contents

C — Parsing a writable character string

In C, strchr finds the first occurrence of a character. In a writable string, replacing that separator with a null byte lets the program read the key and value separately.

A simple example

Split one line of text

  1. Start with "a=b"
  2. Do this Separate at =
  3. Result b
The separator marks where the first field ends and the second begins. Read the second field.
lesson.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char text[] = "a=b";
    char *separator = strchr(text, '=');
    if (separator != NULL) puts(separator + 1);
}
Output
b
Advertisements

Split one setting into a key and a value

strchr returns a pointer to the first separator or NULL. Replacing the separator with a null byte produces two terminated strings in the same writable array. Cast to unsigned char before passing a byte to isspace.

Saved line: city = Lima. Setting name: city. Display value: Lima.
Read a destination from a settings file

A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.

Run the example

C17. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 lesson.c -o lesson
./lesson
lesson.c
#include <stdio.h>
#include <ctype.h>
#include <string.h>

char *trim(char *text) {
    while (isspace((unsigned char)*text)) ++text;
    char *end = text + strlen(text);
    while (end > text && isspace((unsigned char)end[-1])) --end;
    *end = '\0';
    return text;
}

int main(void) {
    char record[] = " city = Lima ";
    char *separator = strchr(record, '=');
    if (separator != NULL) {
        *separator = '\0';
        printf("%s=%s\n", trim(record), trim(separator + 1));
    }
    return 0;
}
Output
city=Lima

The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.

Try it yourself

What should city = A=B produce?

Check your answer

The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.

GNU C Language Manual

Related tags

  • C
  • strings
  • parsing
  • whitespace