Functions for manipulating C-style null-terminated strings and raw memory blocks. Always ensure destination buffers are large enough to avoid buffer-overflow vulnerabilities.
Include: #include <string.h> | Compile: gcc -Wall -o prog prog.c
| Name | Prototype / Value | Description |
|---|---|---|
| strlen | size_t strlen(const char *s) | Length of string (not counting '\0') |
| strcpy | char *strcpy(char *dst, const char *src) | Copy src into dst (unsafe — prefer strncpy) |
| strncpy | char *strncpy(char *dst, const char *src, size_t n) | Copy at most n chars from src to dst |
| strcat | char *strcat(char *dst, const char *src) | Append src to end of dst |
| strncat | char *strncat(char *dst, const char *src, size_t n) | Append at most n chars of src to dst |
| strcmp | int strcmp(const char *a, const char *b) | Compare strings; 0 = equal |
| strncmp | int strncmp(const char *a, const char *b, size_t n) | Compare at most n chars |
| strchr | char *strchr(const char *s, int c) | Find first occurrence of char c in s |
| strrchr | char *strrchr(const char *s, int c) | Find last occurrence of char c in s |
| strstr | char *strstr(const char *hay, const char *needle) | Find first occurrence of substring |
| strtok | char *strtok(char *s, const char *delim) | Split string by delimiter tokens |
| strtok_r | char *strtok_r(char *s, const char *delim, char **save) | Thread-safe strtok |
| memcpy | void *memcpy(void *dst, const void *src, size_t n) | Copy n bytes (no overlap) |
| memmove | void *memmove(void *dst, const void *src, size_t n) | Copy n bytes (handles overlap) |
| memset | void *memset(void *s, int c, size_t n) | Fill n bytes with value c |
| memcmp | int memcmp(const void *a, const void *b, size_t n) | Compare n bytes of memory |
| memchr | void *memchr(const void *s, int c, size_t n) | Find first byte c in n bytes |
| strdup | char *strdup(const char *s) | Duplicate string (malloc'd — caller must free) |
| strerror | char *strerror(int errnum) | Return error description string |
Copy, save as demo.c, and compile with the command shown at the bottom.
#include <stdio.h>
#include <string.h>
int main(void) {
char src[] = "Hello, World!";
char dst[64];
strncpy(dst, src, sizeof(dst) - 1);
dst[sizeof(dst) - 1] = '\0';
printf("dst = \"%s\"\n", dst);
printf("length = %zu\n", strlen(dst));
char *p = strstr(dst, "World");
if (p) printf("Found at index %td\n", p - dst);
char csv[] = "apple,banana,cherry";
char *tok = strtok(csv, ",");
while (tok) { printf("token: %s\n", tok); tok = strtok(NULL, ","); }
char buf[16];
memset(buf, 'A', sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
printf("buf = %s\n", buf);
return 0;
}
/* Compile: gcc -Wall -o str_demo str_demo.c */