是否有可能写的,可以扭转一个字符串不使用缓冲区字符串的函数?
问题描述:
可能重复:结果
How使用指针,以扭转在C处字符串?
面试问题是像 - 编写一个函数调用revstr可以采取一个字符串,扭转它不使用字符串缓冲区即涉及指针等。
The interview question was like - write a function called revstr which can take a string and reverse it without using a buffer string i.e involving pointers etc .
答
从开始迭代,同时结束,互换角色。
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;
}
}
您也可以选择使用XOR技巧无需中间炭交换:
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.