Reverse of String

Program : Reverse String Without Using Library Function [ Strrev ]

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

#define BUFFER_SIZE 100
char buff[BUFFER_SIZE];
int main()
{
        char str[20];
        printf("Enter The string is : ");
        /* gets(str);   // unsafe! */
        fgets( str, sizeof(buff), stdin );   // safe
        int i=0, j=0;
        j = strlen(str)-1;
        while(i<j)
        {
                char tmp;
                tmp = str[j];
                str[j--]=str[i];
                str[i++]= tmp;
        }
        printf("The reverse of string is : %s\n", str);
        return 0;
}


Output :    Enter The string is : Interstellar
                   The reverse of string is : 
                    ralletsretnI

Remember : gets(str): This statement will give warning as : warning: the `gets' function is dangerous and should not be used.

In order to use gets safely, you have to know exactly how many characters that you will be reading so you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.

Instead of using gets, you want to use fgets, which has the signature :

char* fgets(char *string, int length, FILE * stream);
(fgets, if it reads an entire line, will leave the '\n' in the string as in above output; you'll have to deal with that)

Write a recursive C function to print reverse of a given string.

# include <stdio.h>
/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if(*str){
       reverse(str+1);
       printf("%c", *str);
   }
}
/* Driver program to test above function */
int main()
{
   char a[] = "Work Hard";
   reverse(a);
   return 0;
}

Output :
darH kroW

Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way, when pointer reaches ‘\0′, all functions accumulated in stack print char at passed location (str) and return one by one.

Time Complexity: O(n)

No comments:

Post a Comment