String Operations
Use string.h helpers for length, copy, concat, compare, and tokenize.
Code
#include <stdio.h>
#include <string.h>
int main(void) {
char src[] = "Hello, World!";
char dst[32];
// Length (excludes terminator)
printf("len = %zu\n", strlen(src));
// Copy
strcpy(dst, src);
printf("copy = %s\n", dst);
// Concatenation
strcat(dst, " Goodbye.");
printf("concat = %s\n", dst);
// Comparison
printf("cmp = %d\n", strcmp("abc", "abd"));
// Substring search
char *p = strstr(src, "World");
if (p) printf("found at offset %ld\n", (long)(p - src));
// Tokenize
char csv[] = "a,b,c,d";
char *tok = strtok(csv, ",");
while (tok) { printf("tok = %s\n", tok); tok = strtok(NULL, ","); }
return 0;
}Explanation
C strings are NUL-terminated char arrays operated on by string.h functions. strlen, strcpy, strcat, strcmp, and strstr cover the common length, copy, concat, compare, and search operations. strtok splits a string in place by replacing delimiters with NUL bytes and must be re-entered with NULL to continue tokenizing.
More C Snippets
Pointer Basics
Declare pointers, dereference, and walk an array with pointer arithmetic.
Memory Management
Allocate, resize, and free heap memory with malloc, realloc, and free.
File I/O
Open, read, write, and close files using the stdio FILE API.
Structs
Group related fields with typedef and pass by pointer for mutation.
Function Pointers
Store function addresses for callbacks and dispatch tables.
Preprocessor Macros
Define object-like and function-like macros with conditional compilation.