C string.h Library Reference
Complete reference for string.h - strlen, strcpy, strcat, strcmp, searching, and memory functions.
What You Will Learn
- ✓Measure and copy strings
- ✓Compare and concatenate strings
- ✓Search within strings
- ✓Use memory functions safely
01Introduction to string.h
📚 What is string.h?
<string.h> provides functions for string manipulation and memory operations. Essential for working with C strings (null-terminated character arrays).
| Category | Functions |
|---|---|
| Length | strlen |
| Copy | strcpy, strncpy |
| Concatenate | strcat, strncat |
| Compare | strcmp, strncmp, strcasecmp |
| Search | strchr, strrchr, strstr, strtok |
| Memory | memcpy, memmove, memset, memcmp |
02strlen() - String Length
char name[] = "Hello";size_t len = strlen(name);printf("Length: %zu\n", len); // Output: Length: 503String Copy Functions
strcpy() - Copy String
char src[] = "Hello";char dest[20];strcpy(dest, src);printf("%s\n", dest); // Output: Hellostrncpy() - Copy with Limit ⭐
char dest[10];strncpy(dest, "Hello World", sizeof(dest) - 1);dest[sizeof(dest) - 1] = '\0'; // Ensure null termination!printf("%s\n", dest); // Output: Hello Wor⚠️ strncpy() may NOT null-terminate if src is longer than n!
04String Concatenation
strcat() - Append String
char greeting[50] = "Hello";strcat(greeting, " ");strcat(greeting, "World!");printf("%s\n", greeting); // Output: Hello World!strncat() - Append with Limit
char str[20] = "Hello";strncat(str, " World!!!", 6); // Append max 6 charsprintf("%s\n", str); // Output: Hello World05String Comparison
| Function | Prototype | Description |
|---|---|---|
| strcmp() | int strcmp(const char *s1, const char *s2) | Compare two strings |
| strncmp() | int strncmp(s1, s2, size_t n) | Compare first n chars |
| strcasecmp() | int strcasecmp(s1, s2) | Case-insensitive compare |
📊 Return Values
< 0s1 < s2
0s1 == s2
> 0s1 > s2
1int result;23result = strcmp("apple", "banana"); // < 0 (a < b)4result = strcmp("hello", "hello"); // 0 (equal)5result = strcmp("zoo", "apple"); // > 0 (z > a)67// Compare first 3 characters8result = strncmp("Hello", "Help", 3); // 0 (Hel == Hel)910// Case-insensitive (non-standard, use strings.h)11result = strcasecmp("Hello", "HELLO"); // 0 (equal)1213// Common pattern: checking equality14if (strcmp(input, "exit") == 0) {15 printf("Exiting...\n");16}06String Searching
| Function | Prototype | Description |
|---|---|---|
| strchr() | char *strchr(const char *s, int c) | Find first occurrence of char |
| strrchr() | char *strrchr(const char *s, int c) | Find last occurrence of char |
| strstr() | char *strstr(const char *haystack, const char *needle) | Find substring |
| strtok() | char *strtok(char *str, const char *delim) | Tokenize string |
1char str[] = "hello@world.com";23// Find first '@'4char *at = strchr(str, '@');5if (at) printf("Found @: %s\n", at); // @world.com67// Find last '.'8char *dot = strrchr(str, '.');9if (dot) printf("Found .: %s\n", dot); // .com1011// Find substring12char *found = strstr(str, "world");13if (found) printf("Found: %s\n", found); // world.com1415// Tokenize string16char data[] = "apple,banana,cherry";17char *token = strtok(data, ",");18while (token != NULL) {19 printf("Token: %s\n", token);20 token = strtok(NULL, ","); // NULL for subsequent calls!21}⚠️ strtok() Modifies String!
strtok() replaces delimiters with \0and uses static memory. Not thread-safe!
07Secure String Functions (Buffer Overflow Prevention)
🛡️ Why Secure Functions?
Functions like strcpy() and strcat() are dangerous because they don't check buffer sizes. This can cause:
✅ strncpy() - Safer Copy
// DANGEROUS - strcpy has no bounds checkingchar dest[10];strcpy(dest, "This is way too long!"); // Buffer overflow!// SAFE - strncpy limits copychar safe_dest[10];strncpy(safe_dest, "This is way too long!", sizeof(safe_dest) - 1);safe_dest[sizeof(safe_dest) - 1] = '\0'; // Always null-terminate!printf("%s\n", safe_dest); // Output: This is w💡 Important: strncpy may NOT null-terminate if src is longer than n. Always add null terminator manually!
✅ strncat() - Safer Concatenation
char dest[20] = "Hello";// Calculate remaining spacesize_t remaining = sizeof(dest) - strlen(dest) - 1;// Safe concatenationstrncat(dest, " World! More text...", remaining);printf("%s\n", dest); // Output: Hello World! More✅ snprintf() - Safe Formatted String (from stdio.h)
char buffer[20];int age = 25;char *name = "Alice";// Safe - never overflows bufferint written = snprintf(buffer, sizeof(buffer), "%s is %d years old", name, age);printf("%s\n", buffer); // Output: Alice is 25 yearsprintf("Would need: %d chars\n", written); // Would need: 20 chars🔴 Unsafe vs 🟢 Safe Functions
| Unsafe ❌ | Safe ✅ | Why Safer? |
|---|---|---|
| strcpy() | strncpy() | Limits bytes copied |
| strcat() | strncat() | Limits bytes appended |
| sprintf() | snprintf() | Limits output size |
| gets() | fgets() | Limits input size |
💡 Best Practices for Safe String Handling
- • Always use
sizeof(buffer) - 1to leave room for null terminator - • Prefer
snprintf()over sprintf() for formatted strings - • Always manually null-terminate after strncpy()
- • Never use
gets()- it's so dangerous it was removed from C11!
08Memory Functions
| Function | Prototype | Description |
|---|---|---|
| memcpy() | void *memcpy(void *dest, const void *src, size_t n) | Copy n bytes |
| memmove() | void *memmove(void *dest, const void *src, size_t n) | Copy (handles overlap) |
| memset() | void *memset(void *ptr, int value, size_t n) | Fill memory with byte |
| memcmp() | int memcmp(const void *s1, const void *s2, size_t n) | Compare n bytes |
1int src[] = {1, 2, 3, 4, 5};2int dest[5];34// Copy array5memcpy(dest, src, sizeof(src));67// Fill with zeros8memset(dest, 0, sizeof(dest));910// Compare memory11if (memcmp(src, dest, sizeof(src)) == 0) {12 printf("Arrays are equal\n");13}1415// Overlapping memory: use memmove!16char str[] = "Hello World";17memmove(str + 6, str, 5); // "Hello Hello"💡 memcpy vs memmove
Use memmove() when source and destination may overlap. memcpy() is faster but undefined for overlapping regions.
09Summary
🎯 Key Functions
Length/Copy:
strlen, strcpy, strncpy
Concat/Compare:
strcat, strcmp, strncmp
Search:
strchr, strstr, strtok
Memory:
memcpy, memmove, memset
10Next Steps
Learn about mathematical functions: