02. Standard String Handling Functions (<string.h>)
🟢 Difficulty: Beginner | String Length, Copying, Concatenation, Comparison & Tokenization
📖 Definition
The standard C library header <string.h> provides a comprehensive suite of utility functions for operating on null-terminated character strings, including measuring length (strlen), copying memory (strcpy), appending (strcat), lexicographical comparison (strcmp), and searching (strstr, strtok).
🎯 Why It Is Used
- Standardized String Processing: Highly optimized assembly-level implementations for string copying, comparison, and substring searching.
- Lexicographical Sorting: Providing return codes ($<0$, $0$, $>0$) for alphabetical sorting algorithms.
- Text Parsing: Splitting CSV records, URL query strings, or command line input into tokens using
strtok().
⚙️ How It Works: Lexicographical Comparison (strcmp)
The function strcmp(s1, s2) compares strings character-by-character using ASCII character codes:
- Returns
0ifs1ands2are identical. - Returns a negative value (<0) if the first differing character in
s1has a smaller ASCII code than ins2(e.g."Apple"vs"Banana"). - Returns a positive value (>0) if
s1comes lexicographically afters2.
📝 Syntax
#include <string.h>
size_t len = strlen(str); // Measures characters excluding '\0'
char *res = strcpy(dest, src); // Copies src into dest (DEST MUST BE LARGE ENOUGH!)
char *cat = strcat(dest, src); // Appends src onto end of dest
int cmp = strcmp(str1, str2); // Lexicographical comparison
char *match = strstr(haystack, needle);// Substring search (returns pointer or NULL)
char *tok = strtok(str, ","); // Tokenizes string around delimiters
🔀 Key string.h Functions Summary
| Function | Return Value | Primary Purpose |
|---|---|---|
strlen(s) | size_t | Returns character count excluding '\0'. |
strcpy(d, s) | char* (dest pointer) | Copies null-terminated string s into buffer d. |
strcat(d, s) | char* (dest pointer) | Appends string s onto the end of d. |
strcmp(s1, s2) | int (<0, 0, >0) | Compares ASCII character values of two strings. |
strstr(haystack, needle) | char* or NULL | Locates first occurrence of substring needle. |
strtok(s, delim) | char* or NULL | Destructively splits string s into tokens. |
🌱 Beginner Example: Copying & Concatenation
#include <stdio.h>
#include <string.h>
int main(void) {
char first_name[20] = "Dennis";
char last_name[] = "Ritchie";
char full_name[50];
// Copy first_name into full_name
strcpy(full_name, first_name);
strcat(full_name, " ");
strcat(full_name, last_name);
printf("Full Name: %s\n", full_name);
printf("Total String Length: %zu characters\n", strlen(full_name));
return 0;
}
🌼 Intermediate Example: Lexicographical Comparison & Substring Search
#include <stdio.h>
#include <string.h>
int main(void) {
const char *str1 = "Apple";
const char *str2 = "Banana";
int result = strcmp(str1, str2);
if (result < 0) {
printf("\"%s\" comes BEFORE \"%s\" lexicographically.\n", str1, str2);
} else if (result > 0) {
printf("\"%s\" comes AFTER \"%s\" lexicographically.\n", str1, str2);
} else {
printf("Strings are IDENTICAL.\n");
}
const char *sentence = "The C Programming Language";
const char *search_term = "Programming";
char *found_ptr = strstr(sentence, search_term);
if (found_ptr != NULL) {
printf("Found substring \"%s\" at index offset %td!\n",
search_term, found_ptr - sentence);
}
return 0;
}
🌲 Advanced Example: CSV Tokenization using strtok()
#include <stdio.h>
#include <string.h>
int main(void) {
// Note: strtok modifies the string in-place by replacing delimiters with '\0'!
// Therefore, string MUST be in a modifiable stack buffer, NOT a read-only literal!
char csv_record[] = "Alice,88.5,Engineering,Active";
const char *delimiter = ",";
printf("=== Parsing CSV Token Stream ===\n");
// First call: Pass string pointer
char *token = strtok(csv_record, delimiter);
int field_idx = 1;
while (token != NULL) {
printf("Field #%d: %s\n", field_idx++, token);
// Subsequent calls: Pass NULL to continue parsing same string!
token = strtok(NULL, delimiter);
}
return 0;
}
🔍 Line-by-Line Explanation
strcpy(full_name, first_name);: Copies"Dennis"including the null terminator into destination bufferfull_name.strstr(sentence, search_term): Scanssentencefor"Programming", returning a pointer to the matching letter 'P'.token = strtok(csv_record, delimiter);: Replaces the first comma','with'\0'and returns a pointer to"Alice".token = strtok(NULL, delimiter);: PassingNULLinstructsstrtokto resume scanning from the saved internal token offset.
💻 Expected Terminal Output
Full Name: Dennis Ritchie
Total String Length: 14 characters
"Apple" comes BEFORE "Banana" lexicographically.
Found substring "Programming" at index offset 6!
=== Parsing CSV Token Stream ===
Field #1: Alice
Field #2: 88.5
Field #3: Engineering
Field #4: Active
⚠️ Common Mistakes & Pitfalls
- Buffer Overflow with Unbounded
strcpy/strcat: Copying a 100-character string into a 20-character destination buffer corrupts adjacent stack memory! Use bounded functions likesnprintforstrncpyinstead. - Passing Read-Only String Literals to
strtok(): Callingstrtok("A,B,C", ",")causes a Segmentation Fault crash becausestrtokwrites'\0'into the string!
📌 Important Rules & Limitations
- Destination buffers passed to
strcpyandstrcatmust have sufficient space allocated. strtok()is destructive (modifies input string) and non-reentrant (not thread-safe). Usestrtok_r()in multi-threaded code.
🌐 Multilingual Explanation: English
The <string.h> library provides functions for length calculation (strlen), copying (strcpy), concatenation (strcat), comparison (strcmp), and tokenization (strtok).
🌐 Multilingual Explanation: Hindi (Roman Script)
<string.h> library string operations ke liye functions deti hai. Destination buffer hamesha itna bada rakhein ki poori string aur null terminator aasani se fit ho sake.
🌐 Multilingual Explanation: Marathi (Roman Script)
<string.h> library mhadhe string length, copy, compare aani split karnyasathi tayar functions ahet. Destination buffer puresha size cha asava.
❓ Practice Questions
- Why does
strcmp("apple", "banana")return a negative value? - Why does passing a string literal to
strtok()cause a Segmentation Fault? - How does
strtok()know where to resume parsing on subsequent calls whenNULLis passed as the first parameter?
🚀 Practical Coding Challenge
Write a C program named palindrome_checker.c that accepts a word, creates a reversed copy using strcpy and custom reversing, and uses strcmp to check if the word is a palindrome.
🧭 Navigation & Breadcrumbs
← Previous: 01. String Basics | Module 11 Guide | Next: 03. String Traversal & Manipulation →