Hi ,

I am trying to reverse a string using pointers.I am able to reverse a sting like this:
My Reverse Program --> margorp esrever em
But I want it word by word.
Program Reverse My.

#include <stdio.h>
#include <string.h>
 char str[50]="Reversing a string using XOR";
  char strb[50];
  char* strc;
  char strC[50];

char* rev(char* str)
{
	
   char *ptr;
   //ptr = str;
   char *ptrA;
   ptr = strb;
 ptrA= str + strlen(str)-1;
 
printf("i am inside the function %s \n",ptrA);
  int start = 0;

  while( ptrA>=str )
  {
  // printf("i am inside the function while %s\n", ptrA);
  if (ptrA==' ')
  {
	  printf("oh...i found a space");
  }
   *ptr++ = *ptrA--;
  
   
  }
  *ptr = '\0';

printf("i am inside the *********** function %s \n",ptrA);
  return strb;
}

int main()
{
  
  
 // puts(rev(str));
  strc = rev(str);
   puts(strc);
   printf("Reverse String is %s \n",strc);
  
   return 0;
}

Recommended Answers

All 2 Replies

OK, you can try this:

1) Reverse the string
2) Reverse each word in it

eg:

Hello World
1) dlroW olleH --> i guess you have done this part.

Now, reverse each word in it

For this, try this:

for (i = 0 to length(string)) {
        while (string[pos] != SPACE)
               pos++;

        /* Now, use a loop to reverse each separate word 
         * You have obtained the index of the first space. 
         * You have the index of the first word.
         * So, start exchanging characters.
         * So, now you're done with reversing each word.(in each iteration)
         */

         /* Now set i equal to the first character after the space */
}

Here's an example to look at. A note the function modifies the original string so it my not be appropriate for your assignment.

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

char ca[] = "this is the string to tryout on our reverser";

void myfunc(char *s)
{
	int i = 0;
	int len = strlen(s);

	for (i = len; i > 0; --i)
	{
		if (s[i] == ' ')
		{
			s[i] = '\0';
			fprintf(stdout, "%s ", (char*)&s[i + 1]);
			myfunc(s);
			return;
		}
	}
	fputs(s, stdout);
}

int main(int argc, char**argv)
{
	myfunc(ca);
	exit(EXIT_SUCCESS);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.