我正在尝试使用指针反转字符串,但它似乎不起作用,有什么问题吗?输出是 olllo
但应该是 olleh
。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char *cadena){
size_t len = strlen(cadena);
char *end= cadena;
char *aux = cadena;
while(*++end){}
--end; //end points to a
for(;len;--len){
*aux++ = *end--;
}
}
int main()
{
char buffer[] = "hello";
reverse(buffer);
printf("%s",buffer);
return 0;
}
最佳答案
行:
*aux++ = *end--;
不不交换任何东西。它只是将右侧的值赋给左侧。你总是会得到一个回文,由字符串的右半部分组成。对于交换逻辑,您应该这样做:
char tmp = *aux;
*aux = *end;
*end = tmp;
此外,您不应该真正遍历整个字符串。实际上,这意味着反转字符串,然后再次反转。只需在遍历 一半 字符串时应用交换逻辑,就可以开始了:
void reverse(char *cadena) {
if(cadena != NULL){ // add some checks...
size_t len = strlen(cadena);
char *end = cadena + (len > 1 ? len - 1 : 0); // ...for safety
char *aux = cadena;
for (len /= 2; len; --len) {
char tmp = *aux;
*aux++ = *end;
*end-- = tmp;
}
}
}
关于c - 使用指针在c中反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51014507/