开发者

Is it possible write a function that can reverse a string without using a buffer string? [duplicate]

开发者 https://www.devze.com 2023-02-18 15:38 出处:网络
This question already has answers here: Closed 11开发者_如何转开发 years ago. Possible Duplicate:
This question already has answers here: Closed 11开发者_如何转开发 years ago.

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?


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.


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;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消