HOME HTML EDITOR C JAVA PHP

C Strings: Handling Text and Characters

In C, a **String** is a sequence of characters terminated by a null character \0. While other languages have a dedicated "String" type, C treats strings as one-dimensional arrays of type char. This gives programmers granular control over memory but requires a solid understanding of how character arrays work.

1. How Strings are Stored in Memory

When you define a string, C allocates memory for each character in the sequence plus one extra byte for the Null Terminator (\0). This null character tells functions like printf() where the string ends.

For example, the string "HELLO" takes up **6 bytes** of memory, not 5, because of the hidden \0 at the end.

2. Creating and Initializing Strings

There are two primary ways to create a string in C. You can either use a string literal (easiest) or an array of individual characters.

// Method 1: String Literal (Automatically adds \0) char greeting[] = "Hello World";

// Method 2: Character Array (Must manually add \0) char manualGreeting[] = {'H', 'e', 'l', 'l', 'o', '\0'};

// Method 3: Specifying Size char name[20] = "John Doe"; // Reserves 20 bytes

3. Accessing and Modifying Strings

Since a string is an array, you can access individual characters using their **index number**. Just like numeric arrays, the index starts at 0.

char carName[] = "Volvo";
printf("%c", carName[0]); // Prints 'V'

// Modifying a character
carName[0] = 'P';
printf("%s", carName); // Now prints 'Polvo'

4. Special Characters (Escape Sequences)

Because strings are written inside double quotes, you cannot simply put another double quote inside them. To include special symbols, you must use the backslash \ as an escape character.

Escape Sequence Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

5. The String Header File (string.h)

C provides a set of powerful functions to manipulate strings, but you must include the <string.h> library to use them. These functions save you from writing complex loops for simple tasks.

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

int main() {
    char str1[20] = "Hello ";
    char str2[] = "World";

    // Join str2 to str1
    strcat(str1, str2);
    printf("%s", str1); // Output: Hello World
    return 0;
}

6. Important Differences to Remember

Working with strings in C is slightly different than other languages like Python or Java:

Pro Tip: When using scanf() to read a string, it stops at the first whitespace (space, tab, or newline). To read an entire line of text including spaces, use the fgets() function instead.