Thursday, September 28, 2023
HomeC ProgrammingReversing a String | C For Dummies Weblog

Reversing a String | C For Dummies Weblog

The C language is weak in relation to strings. Even the paltry assortment of string.h manipulation capabilities lacks fairly a couple of tips which might be available to different languages. Amongst them is a perform to reverse a string. So why not code your individual?

I name my string reversing perform strrev(). On this perform, storage is allotted for a brand new string, then it’s stuffed ahead whereas processing the unique string backwards. Determine 1 illustrates what my phrases fail to explain.

Determine 1. The method of reversing a string, backwards-copying characters from one to the opposite based mostly on the string’s size.

Right here is the strrev() perform illustrated in code:


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

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

    len = strlen(s);

    reversed = malloc( sizeof(char) * len +1 );
    if( reversed!=NULL )
        s += len -1;        
        i = 0;                
            *(reversed+i) = *s;        
        *(reversed+i) = '';


int major()
    char string[] = "Right here is your pattern string";

    printf("Unique: %sn",string);
    printf("Lanigiro: %sn",strrev(string));


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

Upon success, pointer s is reset to the top of the string, minus one (as a result of the offset begins at zero). Variable i is ready to zero. A whereas loop spins for the size of the unique string, copying characters from *s (the unique, backwards) to *(reversed+i) (the duplicate, in a ahead course). (Determine 1 illustrates how s and i manipulate the 2 string buffers.) (Sorry for all of the parentheticals.)

The brand new, reversed string is capped with a null character at Line 29. String reversed is returned at Line 32. If reminiscence allocation fails, a NULL worth is returned for reversed. I don’t verify for this situation within the major() perform.

Right here is the output:

Unique: Right here is your pattern string
Lanigiro: gnirts elpmas ruoy si ereH

I assume different methods exist to reverse a string. Sooner or later, nevertheless, the code should work the unique string backwards to fill (forwards) the brand new string.

Now that you’ve a backwards string, the apparent query is what to do with it? Hmmm.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments