C has no built-in string type—text is a char array ending with '\0'. <string.h> supplies the standard toolkit: copy (strcpy), join (strcat), measure (strlen), compare (strcmp), and search (strstr). Master these and you can parse input, build messages, and work with files alongside <stdio.h>.
01
strlen
Length.
02
strcpy
Copy.
03
strcat
Append.
04
strcmp
Compare.
05
strstr
Find text.
06
\0
Terminator.
Fundamentals
Definition and Usage
A C string is a sequence of characters stored in consecutive memory, terminated by a null character '\0' (byte value 0). Functions in string.h assume this layout—they read until they see '\0' unless a length limit applies (strncpy, strncat, strncmp).
The header also defines memory helpers—memcpy, memmove, memset, memcmp—that work on raw bytes, not necessarily null-terminated strings.
💡
Beginner Tip
Before strcpy or strcat, know the destination buffer size. A classic bug is char buf[5]; strcpy(buf, "hello!");—six characters plus '\0' do not fit. Use strncpy with manual null termination, or snprintf from <stdio.h>.
Foundation
📝 Syntax
Include the header:
C
#include <string.h>
Common string functions
strlen(s) — length of string (excludes '\0')
strcpy(dest, src) — copy src into dest
strncpy(dest, src, n) — copy at most n characters
strcat(dest, src) — append src to end of dest
strncat(dest, src, n) — append at most n characters
strcmp(a, b) — lexicographic compare; 0 if equal
strncmp(a, b, n) — compare at most n characters
strchr(s, c) — find first occurrence of character c
strstr(haystack, needle) — find first substring
Memory functions (also in string.h)
memcpy(dest, src, n) — copy n bytes (non-overlapping)
memmove(dest, src, n) — copy n bytes (overlapping OK)
memset(dest, value, n) — fill n bytes with value
memcmp(a, b, n) — compare n bytes
Typical patterns
C
size_t len = strlen(msg);
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
if (strcmp(a, b) == 0) { /* equal */ }
char *p = strstr(text, "error");
if (p != NULL) { /* found */ }
Headers and linking
#include <string.h> — uses size_t from <stddef.h>.
str1 must hold "Hello, " + "World!" + '\0' (13 + 1 bytes). strcmp returns 0 when strings match. The old reference output omitted the str3 line—both copies of "World!" compare equal.
Example 2 — strncpy with Manual Null Terminator
Copy only part of a string safely into a fixed buffer.
strncpy(dest, source, 5) copies "Hello" but does not add '\0' if the limit is reached mid-string—you must set dest[5] = '\0'. Safer pattern: strncpy(dest, src, sizeof(dest)-1); dest[sizeof(dest)-1]='\0';
📈 Practical Patterns
Comparison, search, and raw memory.
Example 3 — strcmp and strncmp
Sort order and prefix matching from the reference.
C
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "Hello";
char b[] = "World";
char c[] = "Help";
printf("strcmp(\"Hello\", \"World\"): %d\n", strcmp(a, b));
printf("strncmp(\"Hello\", \"Help\", 3): %d\n", strncmp(a, c, 3));
if (strcmp(a, b) < 0) {
printf("\"Hello\" comes before \"World\"\n");
}
return 0;
}
📤 Output:
strcmp("Hello", "World"): -15
strncmp("Hello", "Help", 3): 0
"Hello" comes before "World"
How It Works
strncmp(a, c, 3) compares only "Hel" vs "Hel"—result 0. Never use == to compare string contents; compare pointers addresses. Use strcmp or strncmp.
Example 4 — strchr and strstr
Find a character and a substring inside a line of text.
C
#include <stdio.h>
#include <string.h>
int main(void) {
char line[] = "Hello, World!";
char *ch = strchr(line, 'W');
char *sub = strstr(line, "World");
if (ch != NULL) {
printf("First 'W' at index %td: \"%s\"\n",
ch - line, ch);
}
if (sub != NULL) {
printf("Found \"World\" at index %td\n", sub - line);
} else {
printf("Substring not found\n");
}
return 0;
}
📤 Output:
First 'W' at index 7: "World!"
Found "World" at index 7
How It Works
Return pointers into the original string—do not free them. Pointer subtraction ch - line gives the index. strrchr finds the last occurrence of a character.
Example 5 — memset (Clear a Buffer)
Zero memory before use—common with buffers from malloc.
memset sets every byte—not the same as assigning a string. Use memset(buf, 0, n) to clear buffers. For copying overlapping regions, use memmove instead of memcpy.
Applications
🚀 Common Use Cases
User input — trim, compare commands with strcmp.
Building paths — strcat directory + filename (with size checks).
Parsing logs — strstr to find keywords like "ERROR".
Sorting names — pass strcmp to qsort from <stdlib.h>.
Tokenizing — combine strchr with loops (or strtok carefully).
Binary data — memcpy/memcmp for structs and buffers.
🧠 How C Strings Work with string.h
1
Char array + \0
Text lives in memory as bytes ending with null.
Layout
2
Functions scan bytes
strlen counts until '\0'; strcpy copies until '\0'.
Algorithm
3
You manage size
C does not track capacity—overflow is your responsibility.
Safety
=
💬
Portable text ops
Same function names on every platform that supports standard C.
Important
📝 Notes
String literals are read-only—do not strcpy into them.
strncpy may pad with zeros if source is shorter than n—surprising but standard.
strtok modifies the string and is not re-entrant—avoid in threaded code.
Do not pass overlapping buffers to strcpy/strcat—use memmove.
strlen is O(n)—cache length if you need it repeatedly in a loop.
Comparing with == checks pointer equality, not string content.
Performance
⚡ Optimization
Standard library string functions are highly tuned. Avoid hand-rolled loops unless profiling proves a bottleneck. Reduce repeated strlen calls, prefer single-pass parsing, and use memcmp for fixed-length binary keys. For many small strings, consider storing length alongside data (common in custom string types).
Wrap Up
Conclusion
<string.h> is essential for text in C. Start with strlen, strcpy, strcat, and strcmp, then add strncpy, strstr, and memory helpers. Always respect buffer sizes and the null terminator.
For deeper coverage of each function, explore the C string functions tutorial series.
string.h is the C standard header for manipulating null-terminated character arrays and raw memory blocks. It provides strcpy, strcat, strlen, strcmp, strncpy, strchr, strstr, memcpy, memset, and related functions used in almost every C program that handles text.
strcpy copies until it hits the source null terminator—if the destination is too small, you get a buffer overflow. strncpy copies at most n bytes but may not add a null terminator if the source is longer than n. After strncpy, set destination[n-1] = '\0' or use snprintf for safer copies.
strcmp compares two strings lexicographically. It returns 0 if they are equal, a negative value if the first string sorts before the second, and a positive value if the first sorts after. Do not assume the values are exactly -1 or 1—only check < 0, == 0, or > 0.
No. strlen returns the number of characters before the terminating '\0'. A string "hi" has length 2. The array must be big enough to hold the characters plus the null byte—"hi" needs at least char buf[3].
strcat appends to the end of the destination string without checking remaining space. You must ensure the destination buffer has room for the existing text, the new text, and the final '\0'. Prefer strncat with a size limit or snprintf to build strings safely.
strchr finds the first occurrence of a single character in a string. strstr finds the first occurrence of a whole substring. Both return a pointer to the match or NULL if not found.
Did you know?
The name string.h is historical—the header also defines memory routines like memcpy that work on any bytes, not only null-terminated text. That is why binary code includes string.h even when no “strings” are involved.