Skip to content

Part 1 · Lesson 9

Strings

On this page

What you'll learn: C strings as char arrays with a null terminator, and the string.h functions strlen, strcpy, strcat and strcmp.

Before you start: Lesson 8.

Up to this point, we've only seen string "literals" (text in double quotes) used directly in printf. We haven't stored or manipulated them.

THE BIG IDEA: C does not have a built-in string data type like many other languages. Instead, a C STRING is simply an ARRAY of characters (char).

But how does the computer know where the string ends in the array?

The Null Terminator

C strings follow a crucial convention: they are "null-terminated". This means a special character, the NULL TERMINATOR \0, is placed after the last actual character in the array to mark the end of the string.

So, the string "Hello" is stored in a char array as:

'H' 'e' 'l' 'l' 'o' '\0'

It requires 6 characters of storage, not 5! This is a very important concept.

All standard C functions that work with strings rely on this \0 character.

The easiest way to declare and initialize a string is to use a string literal. The compiler automatically adds the null terminator \0 for you:

char greeting[] = "Hello, C programmer!";

You could also build a string one character at a time, but then you must add the \0 yourself:

char name[] = {'A', 'l', 'i', 'c', 'e', '\0'};

The %s format specifier in printf is used for strings. When printf receives a char array with %s, it prints characters one by one until it finds the null terminator \0.

Because strings are so common, C provides a standard library of functions to work with them. We included <string.h> at the top to get access.

strlen(): String Length

strlen(message) counts the characters before the \0 (the terminator is not counted). It returns a size_t, an unsigned type for sizes, so it is printed with %zu:

printf("The length of the message (strlen) is: %zu\n", strlen(message));

strcpy(): String Copy

You CANNOT assign one string to another using =. char another_string[20]; another_string = message; <-- THIS IS WRONG!

You must copy the characters from the source to the destination. WARNING: The destination array must be large enough to hold the source string, including its null terminator!

char destination[50];
char source[] = "Some text to be copied.";
strcpy(destination, source);

strcat(): String Concatenate (Join)

This function appends one string to the end of another. WARNING: Again, the destination string must have enough space for the combined result!

char full_greeting[50] = "Welcome, ";
char user[] = "dunamismax";
strcat(full_greeting, user);

strcmp(): String Compare

You CANNOT compare strings using ==. if (str1 == str2) <-- THIS IS WRONG! It compares memory locations, not content.

strcmp() compares two strings lexicographically (like in a dictionary). It returns:

  • 0 if the strings are identical.
  • A negative value if the first string comes before the second.
  • A positive value if the first string comes after the second.

So the test for "the same string" is == 0:

if (strcmp(pass1, pass2) == 0)

"password123" and "Password123" are different, because case matters.

Full Source

9_strings.c 187 lines Download View on GitHub
/**
 * @file 9_strings.c
 * @brief Part 1, Lesson 9: Strings
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson covers how to work with strings, which are one of the most
 * common types of data in programming.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Up to this point, we've only seen string "literals" (text in double quotes)
 * used directly in `printf`. We haven't stored or manipulated them.
 *
 * THE BIG IDEA: C does not have a built-in `string` data type like many other
 * languages. Instead, a C STRING is simply an ARRAY of characters (`char`).
 *
 * But how does the computer know where the string ends in the array?
 *
 * THE NULL TERMINATOR
 * C strings follow a crucial convention: they are "null-terminated". This means
 * a special character, the NULL TERMINATOR `\0`, is placed after the last
 * actual character in the array to mark the end of the string.
 *
 * So, the string "Hello" is stored in a `char` array as:
 * ['H', 'e', 'l', 'l', 'o', '\0']
 * It requires 6 characters of storage, not 5! This is a very important concept.
 *
 * All standard C functions that work with strings rely on this `\0` character.
 */

#include <stdio.h>
#include <string.h> // We must include this new header for string manipulation functions.

int main(void)
{
    // --- Part 1: Declaring and Printing Strings ---

    /*
     * The easiest way to declare and initialize a string is to use a string
     * literal. The compiler automatically adds the null terminator `\0` for you.
     */
    char greeting[] = "Hello, C programmer!";

    printf("--- Part 1: Declaring and Printing Strings ---\n");
    /*
     * The `%s` format specifier in `printf` is used for strings. When `printf`
     * receives a `char` array with `%s`, it prints characters one by one
     * until it finds the null terminator `\0`.
     */
    printf("Our greeting string: %s\n", greeting);

    // Let's prove the null terminator exists. We'll manually initialize one.
    // This is the "hard way" but illustrates the concept perfectly.
    char name[] = {'A', 'l', 'i', 'c', 'e', '\0'};
    printf("A manually created name: %s\n\n", name);

    // --- Part 2: The `<string.h>` Library ---

    /*
     * Because strings are so common, C provides a standard library of functions
     * to work with them. We included `<string.h>` at the top to get access.
     */
    printf("--- Part 2: String Functions ---\n");

    // `strlen()` - String Length
    // This function counts the number of characters in a string *before* the
    // null terminator.
    char message[] = "This is a test.";
    // The length is 15, even though the array size is 16 (to hold the `\0`).
    printf("The message is: \"%s\"\n", message);
    printf("The length of the message (strlen) is: %zu\n", strlen(message));
    // Note: strlen returns a special unsigned integer type `size_t`. We use
    // the `%zu` format specifier to print it correctly and avoid warnings.
    printf("\n");

    // --- Part 3: Copying and Concatenating Strings ---

    printf("--- Part 3: Copying and Concatenating ---\n");

    /*
     * `strcpy()` - String Copy
     * You CANNOT assign one string to another using `=`.
     * `char another_string[20]; another_string = message;` <-- THIS IS WRONG!
     *
     * You must copy the characters from the source to the destination.
     * WARNING: The destination array must be large enough to hold the source
     * string, including its null terminator!
     *
     * `strcpy` does NOT check this for you. It keeps copying until it reaches
     * the source's `\0`, even past the end of the destination. Writing past
     * the end of an array is called a BUFFER OVERFLOW. It is undefined
     * behavior and one of the most common security bugs in C programs.
     *
     * Here it is safe because we chose the sizes: `source` holds 24 characters
     * (23 of text plus the `\0`) and `destination` holds 50. When the source comes
     * from the user or a file, you cannot know its length in advance: check it
     * with `strlen()` before copying (Lesson 17 does this), or read it with a
     * function that is told the destination's size, such as `fgets` (Lesson 14).
     */
    char destination[50]; // A buffer to copy into.
    char source[] = "Some text to be copied.";

    strcpy(destination, source); // Copies `source` into `destination`.
    printf("Result of strcpy: %s\n", destination);

    /*
     * `strcat()` - String Concatenate (join)
     * This function appends one string to the end of another.
     * WARNING: Again, the destination string must have enough space for the
     * combined result! `strcat` does not check either. "Welcome, " (9 characters)
     * plus "dunamismax" (10) plus `\0` needs 20 characters, and we have 50.
     */
    char full_greeting[50] = "Welcome, "; // Initialize with enough space.
    char user[] = "dunamismax";

    strcat(full_greeting, user); // Appends `user` to `full_greeting`.
    printf("Result of strcat: %s\n\n", full_greeting);

    // --- Part 4: Comparing Strings ---

    printf("--- Part 4: Comparing Strings ---\n");

    /*
     * `strcmp()` - String Compare
     * You CANNOT compare strings using `==`.
     * `if (str1 == str2)` <-- THIS IS WRONG! It compares memory locations, not content.
     *
     * `strcmp()` compares two strings lexicographically (like in a dictionary).
     * It returns:
     *   - 0 if the strings are identical.
     *   - A negative value if the first string comes before the second.
     *   - A positive value if the first string comes after the second.
     */
    char pass1[] = "password123";
    char pass2[] = "Password123"; // Case matters!
    char pass3[] = "password123";

    if (strcmp(pass1, pass2) == 0)
    {
        printf("\"%s\" and \"%s\" are the same.\n", pass1, pass2);
    }
    else
    {
        printf("\"%s\" and \"%s\" are different.\n", pass1, pass2);
    }

    if (strcmp(pass1, pass3) == 0)
    {
        printf("\"%s\" and \"%s\" are the same.\n", pass1, pass3);
    }

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * Congratulations on completing Part 1! Strings are a huge concept.
 *
 * Key Takeaways:
 * - A C string is a `char` array ending with a null terminator `\0`.
 * - The `%s` format specifier is used to print strings.
 * - The `<string.h>` header provides essential functions for strings.
 * - `strlen()` gets the length (not including `\0`).
 * - `strcpy()` copies one string to another.
 * - `strcat()` joins one string to the end of another.
 * - Neither `strcpy()` nor `strcat()` checks the destination's size. Make sure
 *   it is big enough, or you get a BUFFER OVERFLOW.
 * - `strcmp()` compares the content of two strings.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the GCC compiler to create an executable file:
 *    `gcc -Wall -Wextra -std=c17 -o 9_strings 9_strings.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./9_strings`
 *    - On Windows (WSL): `./9_strings`
 */

How to Compile and Run

Runs the lesson in Compiler Explorer (GCC 16.2), nothing to install.

Once, before your first lesson

Install Apple's command line tools. They include the cc compiler: xcode-select --install

New to the terminal? The setup guide walks through it.

Build

$ cc -Wall -Wextra -std=c17 -o 9_strings 9_strings.c

Run

$ ./9_strings

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Write a loop that counts the characters in a string without calling strlen, by stopping at '\0'.
  2. Count how many times the letter s appears in message.
  3. Make full_greeting smaller, for example char full_greeting[12], and think about what strcat would do. Why must the destination be big enough?

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/09-strings/ in the repository and on this lesson's page on the website.

Solutions

One worked solution for each exercise above, with the reasoning in its comments. They stay closed until you open them: have a go first, then compare.

Show the solution to exercise 1
1_count_characters.c 54 lines View on GitHub
/**
 * @file 1_count_characters.c
 * @brief Lesson 9, Exercise 1: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Write a loop that counts the characters in a string without calling
 * `strlen`, by stopping at `'\0'`.
 */

#include <stdio.h>
#include <string.h> // Only for strlen(), to check our answer.

int main(void)
{
    char message[] = "This is a test.";

    // Walk along the array until the element is the null terminator. When
    // the loop ends, `length` is the index of the `\0`, which is also the
    // number of characters in front of it.
    int length = 0;
    while (message[length] != '\0')
    {
        length++;
    }

    printf("The message is: \"%s\"\n", message);
    printf("Counted by hand: %d characters\n", length);
    printf("According to strlen: %zu characters\n", strlen(message));

    // An empty string is just a `\0`. The loop condition is false at once,
    // so the count is 0.
    char empty[] = "";
    length = 0;
    while (empty[length] != '\0')
    {
        length++;
    }
    printf("An empty string has %d characters.\n", length);

    return 0;
}

/*
 * This loop is, in essence, what `strlen` does inside. It shows why the null
 * terminator matters so much: nothing else tells the loop where the string
 * stops. If the `\0` were missing, the loop would keep walking past the end
 * of the array into whatever memory comes next.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 1_count_characters 1_count_characters.c
 *   ./1_count_characters
 */
Show the solution to exercise 2
2_count_a_letter.c 46 lines View on GitHub
/**
 * @file 2_count_a_letter.c
 * @brief Lesson 9, Exercise 2: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Count how many times the letter `s` appears in `message`.
 */

#include <stdio.h>

int main(void)
{
    char message[] = "This is a test.";
    int count = 0;

    // Visit every character up to (not including) the null terminator.
    for (int i = 0; message[i] != '\0'; i++)
    {
        // A single character is compared with `==` and SINGLE quotes.
        // (`strcmp` is for whole strings; "s" in double quotes would be a
        // string, not a character.)
        if (message[i] == 's')
        {
            count++;
        }
    }

    printf("The message is: \"%s\"\n", message);
    printf("The letter 's' appears %d times.\n", count); // 3

    return 0;
}

/*
 * The three are in "This", "is" and "test". The comparison is exact, so a
 * capital 'S' would not be counted: 's' and 'S' are different characters
 * with different codes (115 and 83). To count both, test for either one:
 *
 *   if (message[i] == 's' || message[i] == 'S')
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 2_count_a_letter 2_count_a_letter.c
 *   ./2_count_a_letter
 */
Show the solution to exercise 3
3_room_to_append.c 70 lines View on GitHub
/**
 * @file 3_room_to_append.c
 * @brief Lesson 9, Exercise 3: the answer, and a safe version
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Make `full_greeting` smaller, for example `char full_greeting[12]`, and
 * think about what `strcat` would do. Why must the destination be big enough?
 *
 * THE ANSWER:
 * `strcat` would write past the end of the array: a BUFFER OVERFLOW. This
 * program does the arithmetic first and only calls `strcat` when the result
 * fits.
 */

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

int main(void)
{
    char full_greeting[12] = "Welcome, "; // 9 characters + `\0` = 10 of the 12
    char user[] = "dunamismax";           // 10 characters

    // What the joined string needs: every character of both strings, plus
    // one element for the null terminator.
    size_t needed = strlen(full_greeting) + strlen(user) + 1;

    printf("The array holds 12 characters; the joined string needs %zu.\n", needed);

    if (needed <= 12)
    {
        strcat(full_greeting, user);
        printf("Result of strcat: %s\n", full_greeting);
    }
    else
    {
        // 20 does not fit in 12, so this is the branch that runs.
        printf("Not enough room, so strcat was not called.\n");
        printf("full_greeting is still: \"%s\"\n", full_greeting);
    }

    return 0;
}

/*
 * WHAT WOULD HAVE HAPPENED
 *
 * `strcat` is given two addresses and nothing else. It has no idea the
 * destination is 12 elements long. It finds the `\0` of "Welcome, " and
 * starts copying: `d` and `u` fill the last two elements, and the remaining
 * eight characters and the `\0` are written into memory that does not
 * belong to the array.
 *
 * What that memory was being used for decides what you see. The program may
 * crash, another variable may silently change, or it may appear to work
 * today and fail after an unrelated edit. The language makes no promise
 * (this is called undefined behavior; Lesson 37 is all about it), and
 * attackers have used exactly this mistake to take over programs.
 *
 * So the rule from the lesson: the destination must have room for the whole
 * result AND its `\0`, and since `strcat` and `strcpy` will not check, you
 * must.
 *
 * (`size_t` is the unsigned type `strlen` returns. `%zu` prints it.)
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 3_room_to_append 3_room_to_append.c
 *   ./3_room_to_append
 */

Finished this lesson?

Mark it complete to track your progress through the course.

Search the course

Type at least two letters. Press / anywhere to search.

↑ ↓ to choose, Enter to open. On a lesson, j and k go to the next and previous lesson.