目前有两种思路,一个是申请一片辅助空间,然后将原字符串逆向拷贝到辅助空间,然后输出;
另一种是原地逆序,不需要额外的辅助空间,方法就是字符串首尾交换。
#include <stdio.h> #include <string.h> char* str_reverse(char* str) //字符指针 { int n = strlen(str) / 2; int i = 0; char tmp = 0; for (i = 0; i < n; i++) { tmp = str[i]; str[i] = str[strlen(str) - i - 1]; //对调 str[strlen(str) - i - 1] = tmp; } return str; } int main() { char s[] = "hello world!"; printf("str_reverse(s) = %s ", str_reverse(s)); return 0; }
或利用指针特性,直接利用参数,代码如下:
#include <stdio.h> #include <string.h> void str_reverse(char* str) //字符指针 { int n = strlen(str) / 2; int i = 0; char tmp = 0; for (i = 0; i < n; i++) { tmp = str[i]; str[i] = str[strlen(str) - i - 1]; //对调 str[strlen(str) - i - 1] = tmp; } return str; } int main() { char s[] = "hello world!"; str_reverse(s); printf("str_reverse(s) = %s ",s ); return 0; }
from: https://www.cnblogs.com/lvonve/