# **[](https://en.cppreference.com/w/c/header/string)** provides null-terminated string functions (`strlen`, `strcpy`, `strcat`, `strcmp`) and memory operations (`memcpy`, `memmove`, `memset`). Avoid `strcpy`/`strcat` (unsafe); use bounded variants or `snprintf` instead. The `mem*` functions work on raw bytes; the `str*` functions assume null termination. ## Example This example tokenizes a CSV line using `strtok` and measures each field. ```c // compile: gcc -o stringexample stringexample.c // run: ./stringexample // description: tokenize CSV line by comma and print each field #include #include int main() { 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; } ``` ## Common functions **String length**: - `strlen(str)`: length (bytes until null terminator) **String copying** (null-terminated): - `strcpy(dst, src)`: copy string (unsafe: no bounds check, use strncpy) - `strncpy(dst, src, n)`: copy up to n characters (pads with nulls if n > length) - `strdup(src)`: allocate and copy string (POSIX, not standard C) - `strndup(src, n)`: allocate and copy up to n characters (POSIX) **String concatenation** (null-terminated): - `strcat(dst, src)`: append string (unsafe, use strncat) - `strncat(dst, src, n)`: append up to n characters **String comparison** (null-terminated): - `strcmp(s1, s2)`: compare lexicographically (returns <0, 0, or >0) - `strncmp(s1, s2, n)`: compare first n characters - `strcasecmp(s1, s2)`: case-insensitive compare (POSIX) - `strncasecmp(s1, s2, n)`: case-insensitive compare first n (POSIX) **String searching** (null-terminated): - `strchr(str, ch)`: find first occurrence of char (returns pointer or NULL) - `strrchr(str, ch)`: find last occurrence - `strstr(haystack, needle)`: find substring - `strcspn(str, reject)`: length of prefix not containing any reject chars - `strspn(str, accept)`: length of prefix containing only accept chars - `strpbrk(str, accept)`: find first char in accept set **String splitting**: - `strtok(str, delim)`: extract token separated by delim chars (not reentrant) - `strtok_r(str, delim, &ptr)`: reentrant version (POSIX) **Memory operations** (byte-level, works on any data): - `memcpy(dst, src, n)`: copy n bytes (undefined if regions overlap) - `memmove(dst, src, n)`: copy n bytes (safe with overlap) - `memset(dst, byte, n)`: fill n bytes with byte value - `memcmp(s1, s2, n)`: compare n bytes - `memchr(ptr, byte, n)`: find first occurrence of byte - `memccpy(dst, src, byte, n)`: copy until byte found (POSIX)