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?

Nishant
  • 20,354
  • 18
  • 69
  • 101

2 Answers2

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.

Erik
  • 88,732
  • 13
  • 198
  • 189
  • -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 Mar 19 '11 at 12:35
  • @Steve Jessop: The OPs "without using a buffer string" - just demonstrating that you can do it without intermediate storage of the data. – Erik Mar 19 '11 at 12:36
  • 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 Mar 19 '11 at 12:41
  • @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. – Erik Mar 19 '11 at 13:12
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;
   }
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
  • Thanks this was exactly my program in he iview . Hope the iviwer likes it . – Nishant Mar 19 '11 at 12:04
  • Is it possible to read the pointer in the reverse order ? I mean that would just read the string too . – Nishant Mar 19 '11 at 12:11
  • @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. – Heisenbug Mar 19 '11 at 12:14