Reverse String in C

Published on 24 July 2018 (Updated: 15 May 2023)

Welcome to the Reverse String in C page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

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

int main(int argc, char **argv)
{
    char *text = "";
    size_t textlen;

    /* get text from command line and calculate length */
    if (argc >= 2) {
        text = argv[1];
    }

    textlen = strlen(text);

    /* print characters in reverse */
    while (textlen-- > 0) {
        putchar(text[textlen]);
    }

    /* put a newline at the end */
    putchar('\n');

    return 0;
}

Reverse String in C was written by:

This article was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

Approach

We get the length of the input string and iteration from the last character to the first, displaying each character.

Time complexity: O(n)


Breakdown

Now let us see step-by-step how the code works.

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

Here we are including header files (.h files) to use functions like printf(). Header files provided us with tested ready to use functions to ease the software development work.

By including #include <stdio.h> we can use printf() method without worrying about how it is implemented.

int main(int argc, char **argv)
{
    char *text = "";
    size_t textlen;

    /* get text from command line and calculate length */
    if (argc >= 2) {
        text = argv[1];
    }

    textlen = strlen(text);

This get the first command-line argument if it is present. Otherwise, an empty string it assumed. The variable text contains a pointer to the string to be reversed. Then, the length of the string is calculated using strlen() and stored in textlen.

Now we get to actual code that displays the string in reverse:

/* print characters in reverse */
while (textlen-- > 0) {
    putchar(text[textlen]);
}

This goes through the string in reverse order and displays each character.

Then, a newline is displayed:

/* put a newline at the end */
putchar('\n');

Finally the code exits:

return 0;

How to Run the Solution

The easiest way to run this program is to go to this LeetCode Playground and run the program. You can tweak the program or provide different input strings to understand how it works.

Alternatively, you can copy the code from GitHub code and run the program on an online C compiler or in an IDE.