Reversing a String

The C language is weak when it comes to strings. Even the paltry assortment of string.h manipulation functions lacks quite a few tricks that are readily available to other languages. Among them is a function to reverse a string. So why not code your own?

I call my string reversing function strrev(). In this function, storage is allocated for a new string, then it’s filled forward while processing the original string backwards. Figure 1 illustrates what my words fail to describe.

Figure 1. The process of reversing a string, backwards-copying characters from one to the other based on the string’s length.

Here is the strrev() function illustrated in code:

2022_09_24-Lesson.c

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

char *strrev(char *s)
{
    int len,i;
    char *reversed;

    /* obtain string character count */
    len = strlen(s);

    /* +1 for the null character */
    reversed = malloc( sizeof(char) * len +1 );
    /* if memory allocated, fill it with
       the reversed string */
    if( reversed!=NULL )
    {
        s += len -1;        /* last char */
        i = 0;                /* forward index */
        while(len)
        {
            *(reversed+i) = *s;        /* fill */
            i++;            /* move index forward */
            len--;            /* loop counter */
            s--;            /* backward offset */
        }
        /* cap the string */
        *(reversed+i) = '\0';
    }

    return(reversed);
}

int main()
{
    char string[] = "Here is your sample string";

    printf("Original: %s\n",string);
    printf("Lanigiro: %s\n",strrev(string));

    return(0);
}

At Line 11, the string’s length is obtained. This value, len, is used to allocate the new string (Line 14), plus one more character for the terminating null character.

Upon success, pointer s is reset to the end of the string, minus one (because the offset starts at zero). Variable i is set to zero. A while loop spins for the length of the original string, copying characters from *s (the original, backwards) to *(reversed+i) (the duplicate, in a forward direction). (Figure 1 illustrates how s and i manipulate the two string buffers.) (Sorry for all the parentheticals.)

The new, reversed string is capped with a null character at Line 29. String reversed is returned at Line 32. If memory allocation fails, a NULL value is returned for reversed. I don’t check for this condition in the main() function.

Here is the output:

Original: Here is your sample string
Lanigiro: gnirts elpmas ruoy si ereH

I assume other ways exist to reverse a string. At some point, however, the code must work the original string backwards to fill (forwards) the new string.

Now that you have a backwards string, the obvious question is what to do with it? Hmmm.

Leave a Reply