Friday 27 September 2013

Reversing string in c using pointers

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

void print_reverse_string(const char *str)
{
    const char *src = str + strlen(str);
    while (src > str)
        putchar(*--src);
}

void reverse_string_and_print(char *str)
{
    char *src = str;
    char *end = src + strlen(src) - 1;
    while (end > src)
    {
        char t = *end;
        *end-- = *src;
        *src++ = t;
    }
    //return str;
   printf("%s", str);
}

char* reverse_string(char *str)
{
    char *src = str;
    char *end = src + strlen(src) - 1;
    while (end > src)
    {
        char t = *end;
        *end-- = *src;
        *src++ = t;
    }

   return str;
   //printf("%s", str);
}

int  main(void){

    char data[50]= "";

    printf("Enter any string:\n");

    gets(data);

    printf("%s\n", data);
    printf("%s \n", reverse_string(data));
    printf("%s\n", data);

    return(0);
}

I have written the abbove code to reverse an string using pointers. I assume that the above code is self explanatory but still if you want any clarification use the comment section below post.

Peace.

No comments:

Post a Comment