0

Possible Duplicate:
How to reverse a string in place in c using pointers?

The interview question was to write a function called revstr which can take a string and reverse it without using a buffer string i.e involving pointers. How do I do this?

2
  • 3
    See: stackoverflow.com/questions/2124600/… Commented Mar 19, 2011 at 11:56
  • My idea was like is there a way to read the pointer in the opposite direction , that will just achieve the goal ? Commented Mar 19, 2011 at 12:04

2 Answers 2

8

Iterate from beginning and end simultaneously, swap characters.

void revstr(char * str) {
  int right = strlen(str) - 1;
  int left = 0;
  while (left < right) {
    char c = str[right];
    str[right] = str[left];
    str[left] = c;
    ++left;
    --right;
  }
}

Optionally you can use xor tricks to swap without an intermediate char:

str[right] ^= str[left];
str[left] ^= str[right];
str[right] ^= str[left];

This is a purely nonsensical way of doing a swap - the only reason to use this construct is an artificial requirement saying that you can't store string data in intermediate variables and you can't call external functions.

Sign up to request clarification or add additional context in comments.

4 Comments

-0.5 for xor swap. I know it works in this case, since your condition is left < right, but it's premature pessimization. Unless there's a proven need to make the code slower (e.g. the profiler has identified this as a cold spot), why use it?
@Steve Jessop: The OPs "without using a buffer string" - just demonstrating that you can do it without intermediate storage of the data.
Nothing in the C standard guarantees that the normal swap uses intermediate storage, or that the xor swap doesn't, just that one uses an object and the other uses rvalues, so there's a difference in the abstract machine. And anyway, you're "using" more storage for left and right than for c. I'll give you +1 if you edit to "silly xor tricks" ;-p
@Steve Jessop: No explicit extra storage of string data then :P - But you're right, there should be a warning in front of such silly constructs, otherwise people might actually use them in real code.
1

I think that at least you need a char variable to perform a swap operations. You can use something like that:

char buf[SIZE];
   int i ;
   char swap;
      for ( i = 0 ; i < SIZE / 2; i++){
   swap = buf[i];
   buf[i] = buf[SIZE - i];
   buf[SIZE -i] = swap;
   }

3 Comments

Thanks this was exactly my program in he iview . Hope the iviwer likes it .
Is it possible to read the pointer in the reverse order ? I mean that would just read the string too .
@Nishant: i didn't understand exactly what you mean, anyway you can of course starting the cicle from the end of the array and decrementing the pointer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.