Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Strings

What you’ll learn: C strings as char arrays with a null terminator, the string.h functions strlen, strcpy, strcat and strcmp, and snprintf, which builds a string without overflowing its buffer.

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);

snprintf(): Build a String Safely

snprintf works like printf, but writes into a buffer, and you give it the buffer’s size. It never writes past the end: text that does not fit is cut short instead of overflowing. Its return value is how many characters the whole text needed, so you can tell when that happened. When you cannot be sure a result fits, use snprintf instead of strcpy and strcat.

char short_greeting[10];
int needed = snprintf(short_greeting, sizeof(short_greeting), "Welcome, %s", 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

/**
 * @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", full_greeting);

    /*
     * `snprintf()` - the bounded way to build a string
     * `snprintf` works like `printf`, but it writes into a buffer instead of
     * the screen, and you tell it the buffer's size. It never writes more than
     * that, `\0` included: text that does not fit is cut short instead of
     * overflowing. When you cannot be sure a result fits, as with text a user
     * typed, use `snprintf` instead of `strcpy` and `strcat`.
     *
     * Here the buffer holds 10 characters, so only "Welcome, " (9) and the
     * `\0` fit. `snprintf` returns how many characters the WHOLE text needed;
     * if that is not less than the buffer's size, the text was cut short.
     * (`sizeof` gives a `size_t`; 10 fits in an `int`, so the cast is safe.)
     */
    char short_greeting[10];
    int needed = snprintf(short_greeting, sizeof(short_greeting), "Welcome, %s", user);
    printf("Result of snprintf: %s\n", short_greeting);
    if (needed >= (int)sizeof(short_greeting))
    {
        printf("(Cut short safely: the whole text needs %d characters.)\n", needed);
    }
    printf("\n");

    // --- 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.
 * - `snprintf()` builds a string in a buffer of a size you give it and never
 *   writes past the end; use it when the text might not fit.
 * - `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 C compiler, `cc`, to create an executable file:
 *    `cc -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

cc -Wall -Wextra -std=c17 -o 9_strings 9_strings.c
./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.