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 0 if s1 and s2 are identical.
  • Returns a negative value (<0) if the first differing character in s1 has a smaller ASCII code than in s2 (e.g. "Apple" vs "Banana").
  • Returns a positive value (>0) if s1 comes lexicographically after s2.

📝 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_tReturns 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 NULLLocates first occurrence of substring needle.
strtok(s, delim)char* or NULLDestructively 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 buffer full_name.
  • strstr(sentence, search_term): Scans sentence for "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);: Passing NULL instructs strtok to 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 like snprintf or strncpy instead.
  • Passing Read-Only String Literals to strtok(): Calling strtok("A,B,C", ",") causes a Segmentation Fault crash because strtok writes '\0' into the string!

📌 Important Rules & Limitations

  • Destination buffers passed to strcpy and strcat must have sufficient space allocated.
  • strtok() is destructive (modifies input string) and non-reentrant (not thread-safe). Use strtok_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

  1. Why does strcmp("apple", "banana") return a negative value?
  2. Why does passing a string literal to strtok() cause a Segmentation Fault?
  3. How does strtok() know where to resume parsing on subsequent calls when NULL is 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 →