Skip to content
AgileLogics
5 min read

String Manipulation in Depth

Prerequisites: The standard library: an overview

A few more <string.h> functions that come up constantly, plus their safer, bounds-aware counterparts:

char buf[10];
strncpy(buf, "Hello, world!", sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0'; // strncpy doesn't always null-terminate

char *found = strstr("Hello, world!", "world");
printf("%s\n", found); // "world!" — from the match onward

char *token = strtok(buf, ",");
while (token != NULL) {
    printf("%s\n", token);
    token = strtok(NULL, ",");
}

Prefer strncpy/snprintf over strcpy/sprintf in real code — the "n" versions take a maximum length, preventing a source string from overflowing a fixed-size destination buffer.

Common mistakes

  • Assuming strncpy always null-terminates the destination — if the source is exactly as long as (or longer than) the limit, it won't; add the terminator manually as shown above.