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

Reversing a string in place

Reversing a string in place

What you'll learn: How to efficiently flip the order of characters in a string without using extra memory for a second array.

The Two-Pointer Approach

To reverse a string "in place" means we modify the original array directly rather than creating a copy. The most efficient way to do this is the Two-Pointer technique.

Imagine you have a row of students standing in a line, and you want them to reverse their order. You don’t need a second room to move them into. Instead, you just have the student at the very front swap places with the student at the very back. Then, the second student swaps with the second-to-last, and you keep moving inward until your "pointers" meet in the middle.

Swapping in C

In C, we use two index variables: start (beginning at 0) and end (the last character before the null terminator). We swap the characters at these positions using a temporary variable, increment start, decrement end, and repeat until they cross paths.

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

void reverseString(char str[]) {
    int start = 0;
    int end = strlen(str) - 1;
    char temp;

    while (start < end) {
        // Swap characters using a temporary holder
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;

        // Move the pointers toward the center
        start++;
        end--;
    }
}

int main() {
    char word[] = "C Programming";
    reverseString(word);
    printf("Reversed: %s", word); // Output: gnimmargorP C
    return 0;
}

Why stop in the middle?

A common mistake is to loop through the entire length of the string. However, if you swap every character all the way to the end, you will end up reversing the string twice—effectively putting it back in its original order! By stopping the while loop once start is no longer less than end, you ensure each pair is swapped exactly once.

This algorithm is highly efficient because it has a time complexity of O(n) and uses O(1) extra space, making it the gold standard for simple string manipulation.

Key takeaway

Reversing in place uses two pointers moving inward from the ends to swap characters until they meet in the center.