C Strings

Working with text and character sequences

📝 What are Strings in C?

Strings in C are arrays of characters terminated by a null character ('\0'). They represent text data and are fundamental for handling names, messages, and any textual information in programs.


// String example
char name[20] = "Hello World";
printf("String: %s", name);
printf("First character: %c", name[0]);
                                    

String Fundamentals

🔤

Character Arrays

Strings are char arrays

char str[10] = "Hello";
🔚

Null Terminator

Strings end with '\0'

char str[] = {'H','i','\0'};
📏

String Length

Count characters before '\0'

int len = strlen("Hello");
🔄

String Operations

Copy, compare, concatenate

strcpy(dest, source);

🔹 String Declaration and Initialization

Strings in C are character arrays terminated with a null character '\0' that marks the string's end. Declare and initialize strings using char str[] = "Hello"; or char str[10] = "Hello"; to set fixed buffer sizes. The compiler automatically adds the null terminator. Understanding proper string declaration prevents buffer overflow vulnerabilities and ensures strings function correctly with standard library functions designed for null-terminated strings.

// Method 1: Character array with size
char str1[20] = "Hello";

// Method 2: Let compiler determine size
char str2[] = "World";

// Method 3: Character by character
char str3[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

// Method 4: Initialize empty string
char str4[50] = "";  // Empty string

// Method 5: String literal (read-only)
char *str5 = "Constant string";

Memory Layout:

str1: ['H']['e']['l']['l']['o']['\0'][...unused...]

str2: ['W']['o']['r']['l']['d']['\0']

str3: ['H']['e']['l']['l']['o']['\0']

🔹 String Input and Output

Reading and displaying strings uses functions like scanf(), gets(), fgets(), and printf(). Use scanf("%s", str) for simple input or fgets(str, size, stdin) for safer buffered input with size limits. Output strings using printf("%s", str) or puts(str). Proper input/output handling prevents security issues and enables interactive programs that communicate effectively with users.

#include <stdio.h>

int main() {
    char name[50];
    char message[100];
    
    // Output strings
    printf("Enter your name: ");
    
    // Input methods
    scanf("%s", name);          // Reads until space
    getchar();                  // Consume newline
    
    printf("Enter a message: ");
    fgets(message, 100, stdin); // Reads entire line
    
    // Output
    printf("Hello, %s!\n", name);
    printf("Your message: %s", message);
    
    return 0;
}

Sample Run:

Enter your name: John

Enter a message: Hello World!

Hello, John!

Your message: Hello World!

🔹 String Manipulation

Manipulating individual characters in strings involves accessing them by index and modifying their values. Use str[i] = character to change characters at specific positions, or iterate through the string using loops. Common manipulations include converting cases, replacing characters, or building new strings character-by-character. Understanding character-level manipulation enables creating utilities for text transformation and pattern processing in C.

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

int main() {
    char str[] = "Programming";
    
    // Access individual characters
    printf("First character: %c\n", str[0]);        // P
    printf("Last character: %c\n", str[10]);        // g
    
    // Modify characters
    str[0] = 'p';  // Change P to p
    printf("Modified string: %s\n", str);           // programming
    
    // String length
    printf("Length: %d\n", strlen(str));            // 11
    
    // Loop through characters
    printf("Characters: ");
    for(int i = 0; str[i] != '\0'; i++) {
        printf("%c ", str[i]);
    }
    printf("\n");
    
    return 0;
}

Output:

First character: P

Last character: g

Modified string: programming

Length: 11

Characters: p r o g r a m m i n g

🔹 Basic String Operations

Essential string operations without library functions teach fundamental programming concepts through manual implementation. Manually counting string length, copying strings character-by-character, concatenating strings, and comparing strings develop deeper understanding of C's string handling. These operations involve iterating through arrays with loops and null-terminator awareness. Learning basic operations strengthens your programming skills and clarifies how standard library functions work internally.

Calculate String Length:

int stringLength(char str[]) {
    int length = 0;
    while(str[length] != '\0') {
        length++;
    }
    return length;
}

Copy String:

void copyString(char dest[], char source[]) {
    int i = 0;
    while(source[i] != '\0') {
        dest[i] = source[i];
        i++;
    }
    dest[i] = '\0';  // Add null terminator
}

Compare Strings:

int compareStrings(char str1[], char str2[]) {
    int i = 0;
    while(str1[i] != '\0' && str2[i] != '\0') {
        if(str1[i] != str2[i]) {
            return 0;  // Not equal
        }
        i++;
    }
    return (str1[i] == '\0' && str2[i] == '\0');
}

🔹 Common String Problems

Practice solving common string challenges like counting vowels, reversing strings, checking palindromes, and removing spaces. These exercises reinforce understanding of loops, conditional statements, and character manipulation. For example, reversing a string involves reading from end to beginning, counting vowels requires checking each character against a vowel set, and removing characters involves selectively copying characters. Solving these problems builds practical skills applicable to real-world text processing applications.

#include <stdio.h>

// Count vowels in a string
int countVowels(char str[]) {
    int count = 0;
    for(int i = 0; str[i] != '\0'; i++) {
        char c = str[i];
        if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
           c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
            count++;
        }
    }
    return count;
}

// Reverse a string
void reverseString(char str[]) {
    int length = 0;
    while(str[length] != '\0') length++;  // Find length
    
    for(int i = 0; i < length/2; i++) {
        char temp = str[i];
        str[i] = str[length-1-i];
        str[length-1-i] = temp;
    }
}

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

Output:

Original: Hello World

Vowels: 3

Reversed: dlroW olleH

🧠 Test Your Knowledge

What character marks the end of a string in C?