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
- Start with "a=b"
- Do this Separate at =
- Result b
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "a=b";
char *separator = strchr(text, '=');
if (separator != NULL) puts(separator + 1);
}
b
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.
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
#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;
}
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.