Table of Contents

string.h

String manipulation in C means working directly with pointers into null-terminated byte arrays. string.h provides the standard set of functions for this: measuring lengths, copying, concatenating, comparing, searching, and operating on raw memory blocks. The string functions work on char *; the memory functions (mem*) work on void * and treat data as raw bytes.

#include <string.h>
 
// length
size_t n = strlen("hello");   // 5 — does not count the null terminator
 
// copy and concatenate
char dst[64];
strcpy(dst, "hello");         // copies including null terminator
strcat(dst, " world");        // appends; dst must have room
strncpy(dst, src, sizeof(dst) - 1);  // bounded copy, may not null-terminate
strncat(dst, src, sizeof(dst) - strlen(dst) - 1); // bounded append
 
// compare
strcmp("abc", "abc")    // 0
strcmp("abc", "abd")    // negative (c < d)
strncmp(a, b, 3)        // compare at most 3 characters
 
// search
char *p = strchr(s, 'x');    // first occurrence of 'x', NULL if absent
char *q = strrchr(s, 'x');   // last occurrence
char *r = strstr(s, "sub");  // first occurrence of substring
 
// memory
memcpy(dst, src, n);   // copy n bytes; regions must not overlap
memmove(dst, src, n);  // copy n bytes; handles overlap safely
memset(ptr, 0, n);     // fill n bytes with 0
memcmp(a, b, n);       // compare n bytes, returns <0, 0, or >0

strcpy and strcat are unsafe when the destination is too small: they write past the end with no error. The bounded variants (strncpy, strncat) prevent the overflow but carry their own pitfall: strncpy does not guarantee null-termination when the source is longer than the limit. The safest portable alternative is snprintf(dst, size, "%s", src), which always null-terminates.

strtok(str, delim) splits a string in place by replacing delimiter characters with null bytes and returning a pointer to each token on successive calls. Pass NULL as the first argument after the first call to continue tokenising the same string. It is not reentrant; strtok_r is the thread-safe version.

Practice

// compile: gcc -o strdemo strdemo.c
// run: ./strdemo
// description: tokenise a CSV line and measure each field
 
#include <string.h>
#include <stdio.h>
 
int main(void) {
    char line[] = "alice,30,engineer,london";
    char *tok = strtok(line, ",");
    int  field = 0;
 
    while (tok) {
        printf("field %d: \"%s\" (len %zu)\n", field++, tok, strlen(tok));
        tok = strtok(NULL, ",");
    }
    return 0;
}

Notice that line is declared as an array, not a string literal — strtok writes null bytes into the buffer in place, so passing a read-only string literal would be undefined behaviour.