String Handling

Introduction

String handling in C involves working with sequences of characters stored as arrays. Since C doesn’t have a built-in string data type, strings are represented as null-terminated character arrays. Understanding string manipulation is essential for text processing, user input handling, and many practical programming tasks.

Key Concepts

Null Terminator: Strings end with ‘\0’ character Character Array: Strings are arrays of char type String Literals: Text enclosed in double quotes String Functions: Library functions in string.h for manipulation

String Declaration and Initialization

Different Ways to Declare Strings

#include <stdio.h>
#include <string.h>

int main() {
    // Method 1: Character array with size
    char str1[20];
    
    // Method 2: Initialize with string literal
    char str2[] = "Hello World";
    
    // Method 3: Character array with explicit initialization
    char str3[] = {'H', 'e', 'l', 'l', 'o', '\0'};
    
    // Method 4: Fixed size with initialization
    char str4[50] = "Programming";
    
    // Method 5: String pointer (read-only)
    char *str5 = "Constant String";
    
    printf("str2: %s\n", str2);
    printf("str3: %s\n", str3);
    printf("str4: %s\n", str4);
    printf("str5: %s\n", str5);
    
    return 0;
}

Basic String Input/Output

Reading and Printing Strings

#include <stdio.h>

int main() {
    char name[50];
    char city[30];
    
    printf("Enter your name: ");
    scanf("%s", name);  // Reads until whitespace
    
    printf("Enter your city: ");
    getchar();  // Consume newline left by scanf
    fgets(city, sizeof(city), stdin);  // Reads entire line
    
    printf("Hello %s from %s", name, city);
    
    return 0;
}

Safe String Input

#include <stdio.h>
#include <string.h>

int main() {
    char input[100];
    
    printf("Enter a sentence: ");
    if (fgets(input, sizeof(input), stdin) != NULL) {
        // Remove newline if present
        size_t len = strlen(input);
        if (len > 0 && input[len-1] == '\n') {
            input[len-1] = '\0';
        }
        printf("You entered: %s\n", input);
    }
    
    return 0;
}

Essential String Functions

String Length (strlen)

#include <stdio.h>
#include <string.h>

int main() {
    char text[] = "Programming";
    
    printf("String: %s\n", text);
    printf("Length: %zu\n", strlen(text));
    
    // Manual length calculation
    int length = 0;
    while (text[length] != '\0') {
        length++;
    }
    printf("Manual length: %d\n", length);
    
    return 0;
}

String Copy (strcpy, strncpy)

#include <stdio.h>
#include <string.h>

int main() {
    char source[] = "Hello World";
    char dest1[50];
    char dest2[50];
    
    // Copy entire string
    strcpy(dest1, source);
    printf("Copied string: %s\n", dest1);
    
    // Copy first n characters
    strncpy(dest2, source, 5);
    dest2[5] = '\0';  // Manually add null terminator
    printf("Partial copy: %s\n", dest2);
    
    return 0;
}

String Concatenation (strcat, strncat)

#include <stdio.h>
#include <string.h>

int main() {
    char str1[50] = "Hello ";
    char str2[] = "World";
    char str3[50] = "Good ";
    
    // Concatenate strings
    strcat(str1, str2);
    printf("Concatenated: %s\n", str1);
    
    // Concatenate n characters
    strncat(str3, "Morning Everyone", 7);
    printf("Partial concatenation: %s\n", str3);
    
    return 0;
}

String Comparison (strcmp, strncmp)

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "apple";
    char str2[] = "banana";
    char str3[] = "apple";
    
    // Compare strings
    int result1 = strcmp(str1, str2);
    int result2 = strcmp(str1, str3);
    
    printf("Comparing '%s' and '%s': %d\n", str1, str2, result1);
    printf("Comparing '%s' and '%s': %d\n", str1, str3, result2);
    
    if (strcmp(str1, str3) == 0) {
        printf("Strings are equal\n");
    }
    
    // Compare first n characters
    if (strncmp("hello", "help", 3) == 0) {
        printf("First 3 characters match\n");
    }
    
    return 0;
}

String Searching Functions

Character Search (strchr, strrchr)

#include <stdio.h>
#include <string.h>

int main() {
    char text[] = "programming";
    char ch = 'r';
    
    // Find first occurrence
    char *first = strchr(text, ch);
    if (first != NULL) {
        printf("First '%c' found at position: %ld\n", ch, first - text);
    }
    
    // Find last occurrence
    char *last = strrchr(text, ch);
    if (last != NULL) {
        printf("Last '%c' found at position: %ld\n", ch, last - text);
    }
    
    return 0;
}

Substring Search (strstr)

#include <stdio.h>
#include <string.h>

int main() {
    char text[] = "The quick brown fox jumps";
    char pattern[] = "brown";
    
    char *found = strstr(text, pattern);
    if (found != NULL) {
        printf("Pattern '%s' found at position: %ld\n", pattern, found - text);
        printf("Remaining text: %s\n", found);
    } else {
        printf("Pattern not found\n");
    }
    
    return 0;
}

Practical String Applications

Word Count Program

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int countWords(char *str) {
    int count = 0;
    int inWord = 0;
    
    for (int i = 0; str[i] != '\0'; i++) {
        if (isspace(str[i])) {
            inWord = 0;
        } else if (!inWord) {
            inWord = 1;
            count++;
        }
    }
    return count;
}

int main() {
    char sentence[200];
    
    printf("Enter a sentence: ");
    fgets(sentence, sizeof(sentence), stdin);
    
    printf("Word count: %d\n", countWords(sentence));
    
    return 0;
}

String Reversal

#include <stdio.h>
#include <string.h>

void reverseString(char *str) {
    int len = strlen(str);
    int start = 0;
    int end = len - 1;
    
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}

int main() {
    char text[] = "Hello World";
    
    printf("Original: %s\n", text);
    reverseString(text);
    printf("Reversed: %s\n", text);
    
    return 0;
}

Palindrome Check

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int isPalindrome(char *str) {
    int left = 0;
    int right = strlen(str) - 1;
    
    while (left < right) {
        // Skip non-alphabetic characters
        while (left < right && !isalpha(str[left])) left++;
        while (left < right && !isalpha(str[right])) right--;
        
        if (tolower(str[left]) != tolower(str[right])) {
            return 0;
        }
        left++;
        right--;
    }
    return 1;
}

int main() {
    char text[] = "A man a plan a canal Panama";
    
    printf("Text: %s\n", text);
    if (isPalindrome(text)) {
        printf("It's a palindrome!\n");
    } else {
        printf("Not a palindrome.\n");
    }
    
    return 0;
}

String Tokenization

#include <stdio.h>
#include <string.h>

int main() {
    char sentence[] = "apple,banana,orange,grape";
    char *token;
    int count = 1;
    
    printf("Original string: %s\n", sentence);
    printf("Tokens:\n");
    
    token = strtok(sentence, ",");
    while (token != NULL) {
        printf("%d. %s\n", count++, token);
        token = strtok(NULL, ",");
    }
    
    return 0;
}

String Conversion Functions

Case Conversion

#include <stdio.h>
#include <ctype.h>

void toUpperCase(char *str) {
    for (int i = 0; str[i]; i++) {
        str[i] = toupper(str[i]);
    }
}

void toLowerCase(char *str) {
    for (int i = 0; str[i]; i++) {
        str[i] = tolower(str[i]);
    }
}

int main() {
    char text1[] = "Hello World";
    char text2[] = "PROGRAMMING";
    
    printf("Original: %s\n", text1);
    toUpperCase(text1);
    printf("Uppercase: %s\n", text1);
    
    printf("Original: %s\n", text2);
    toLowerCase(text2);
    printf("Lowercase: %s\n", text2);
    
    return 0;
}

Common Mistakes and Solutions

Buffer Overflow Prevention

#include <stdio.h>
#include <string.h>

int main() {
    char dest[10];
    char source[] = "This is a very long string";
    
    // Dangerous - no bounds checking
    // strcpy(dest, source);  // Buffer overflow!
    
    // Safe approach
    strncpy(dest, source, sizeof(dest) - 1);
    dest[sizeof(dest) - 1] = '\0';  // Ensure null termination
    
    printf("Safe copy: %s\n", dest);
    
    return 0;
}

Proper String Comparison

#include <stdio.h>
#include <string.h>

int main() {
    char *str1 = "hello";
    char *str2 = "hello";
    char str3[] = "hello";
    
    // Wrong way - compares addresses
    if (str1 == str3) {
        printf("This may not work as expected\n");
    }
    
    // Correct way - compares content
    if (strcmp(str1, str3) == 0) {
        printf("Strings are equal\n");
    }
    
    return 0;
}

Best Practices

  1. Always Check Bounds: Use functions like strncpy, strncat
  2. Null Termination: Ensure strings are properly terminated
  3. Input Validation: Validate user input for security
  4. Use fgets: Prefer fgets over gets for input
  5. Memory Management: Be careful with dynamic string allocation

Summary

String handling in C requires careful attention to memory management and null termination. Key functions from string.h library provide essential operations like copying, concatenation, comparison, and searching. Understanding these fundamentals enables effective text processing, user input handling, and data manipulation in C programs. Always prioritize safety by using bounded string functions and proper input validation.


Part of BCA Programming with C Course (UGCOA22J201)