C - Purpose of string.h
In C, string.h
is the String Handling Header File.
It contains function prototypes and macros for manipulating C-style strings (null-terminated character arrays) and working with blocks of memory.
1. Purpose of string.h
When you include:
#include <string.h>
you gain access to:
-
String manipulation (copying, concatenation, comparison).
-
Searching within strings.
-
Measuring string lengths.
-
Memory block operations (
memcpy
,memmove
, etc.).
These functions work with char arrays — not C++ string
objects.
2. Commonly Used Functions in string.h
a) String Length
Function | Description |
---|---|
strlen(s) |
Returns the length of string s (excluding \0 ). |
b) Copying Strings
Function | Description |
---|---|
strcpy(dest, src) |
Copies src to dest (until \0 ). |
strncpy(dest, src, n) |
Copies up to n characters from src to dest . |
c) Concatenation
Function | Description |
---|---|
strcat(dest, src) |
Appends src to end of dest . |
strncat(dest, src, n) |
Appends up to n characters from src . |
d) Comparison
Function | Description |
---|---|
strcmp(s1, s2) |
Compares strings lexicographically (<0 , 0 , >0 ). |
strncmp(s1, s2, n) |
Compares up to n characters. |
e) Searching
Function | Description |
---|---|
strchr(s, c) |
Returns pointer to first occurrence of c in s . |
strrchr(s, c) |
Returns pointer to last occurrence of c in s . |
strstr(s1, s2) |
Finds first occurrence of substring s2 in s1 . |
f) Memory Operations
Function | Description |
---|---|
memcpy(dest, src, n) |
Copies n bytes from src to dest (no overlap). |
memmove(dest, src, n) |
Copies n bytes (safe for overlapping). |
memset(s, c, n) |
Sets n bytes in s to value c . |
memcmp(s1, s2, n) |
Compares n bytes of two memory blocks. |
3. Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = "World";
// Concatenate
strcat(str1, " ");
strcat(str1, str2);
printf("After concatenation: %s\n", str1);
// Length
printf("Length: %zu\n", strlen(str1));
// Copy
char str3[20];
strcpy(str3, str1);
printf("Copy: %s\n", str3);
// Compare
if (strcmp(str1, str3) == 0) {
printf("Strings are equal\n");
}
// Search
char *pos = strstr(str1, "World");
if (pos) {
printf("Found 'World' at position: %ld\n", pos - str1);
}
return 0;
}
4. Important Notes
-
All strings in C are null-terminated (
\0
at the end). -
Functions like
strcpy
andstrcat
can cause buffer overflows if the destination is too small. -
Safer versions like
strncpy
or platform-specificstrlcpy
are preferred in modern C.