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;
}
精彩评论