Thread: reverse a string

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Nov 2007
    Location
    Bangalore, India
    Posts
    24
    I would suggest that you reverse the string in place and then print it with "%s" format specifier. That way you save multiple calls to printf.

  2. #2
    Dragon Rider jas_atwal's Avatar
    Join Date
    Nov 2007
    Location
    India
    Posts
    54
    Quote Originally Posted by pankaj401 View Post
    I would suggest that you reverse the string in place and then print it with "%s" format specifier. That way you save multiple calls to printf.
    Thank you so much for your suggestion. I have made some changes to my code taking your suggestion:
    Code:
    //This is a small program to reverse the string provided by user
    #include<stdio.h>
    #include<string.h>
    
    int main() {
     char string[256], revstr[256];
     int len, i;
    
     printf("Enter a string:\n");
     fgets(string, 256-1, stdin);
     len = (strlen(string) - 1);
     printf("You entered %s \nlength %d:\n", string, len);
     i = len;
     printf("Reverse string:");
     for(; len >= 0; len--)
            revstr[i-len] = string[len];
    
     revstr[i+1] = '\0';
     printf("Reversed string is: %s\n", revstr);
     exit(0);
    }

  3. #3
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    You could reverse the string by swapping characters up to half way through the string with the corresponding characters on the other half of the string. Just a different way of doing it:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void Reverse(char* string)
    {
    	int len = strlen(string)-1;
    	int mid = len / 2;
    	int pos;
    	char tmp;
    
    	for(pos=0; pos<mid; pos++)
    	{
     		tmp = string[pos];
    		string[pos]	= string[len-pos];
    		string[len-pos] = tmp;
    	}		
    }
    
    int main()
    {
    	char string[256];
    	fgets(string, 256, stdin);
    	string[strlen(string)-1]='\0';
    	printf("Normal: %s\n", string);
    	Reverse(string);
    	printf("Reversed: %s\n", string);
    	Reverse(string);
    	printf("Back again: %s\n", string);
    	getchar();
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM