Course contentsShow
← C
Lesson 444 of 1,2196. Arrays and StringsFree lesson

Removing a character from a string

Removing a character from a string

What you'll learn: How to delete a specific character from a string by shifting subsequent characters to the left.

In C, strings are stored in fixed-size arrays. Because memory is contiguous, you can’t simply "pluck" a character out and leave a hole. If you have the word "CHART" and want to remove the 'H', you can't just delete it; you would be left with C _ A R T. To properly remove a character, you must slide all the letters to the right of the gap one space to the left, effectively overwriting the unwanted character and closing the gap.

The "Moving Walkway" Approach

Imagine a line of people standing on a moving walkway. If one person jumps off, everyone behind them must take one step forward to keep the line tight.

In code, we achieve this using two pointers (or indices):

  1. A Reader that looks at every character in the original string.
  2. A Writer that only writes down the characters we want to keep.

When the Reader finds the character we want to delete, it simply skips over it. The Writer stays put, waiting for the next "good" character to arrive. When the Reader finds a character we want to keep, the Writer copies it to its current position and then moves forward one spot.

Implementation in C

Here is how you can remove all occurrences of the letter 'x' from a string:

#include <stdio.h>

void removeCharacter(char* str, char junk) {
    int reader = 0;
    int writer = 0;

    while (str[reader] != '\0') {
        // If the current character is NOT the one we want to remove
        if (str[reader] != junk) {
            // Copy it to the writer's position
            str[writer] = str[reader];
            // Move the writer forward
            writer++;
        }
        // Always move the reader forward
        reader++;
    }

    // Crucial step: Null-terminate the new, shorter string
    str[writer] = '\0';
}

int main() {
    char myString[] = "Exxcxelllent";
    removeCharacter(myString, 'x');
    printf("%s", myString); // Outputs: Excellent
    return 0;
}

Why the Null Terminator matters

The array size doesn't change when you remove a character. The memory for "Exxcxelllent" is still there. By placing a new \0 (null terminator) at the writer position, you tell C that the string ends earlier than it used to. Everything after that new null terminator is ignored, effectively "shortening" the string.

Key takeaway

To remove a character, overwrite it by shifting subsequent characters one position to the left and manually placing a new null terminator to mark the new end.