字符串逆序函数-- c语言
目前有两种思路,一个是申请一片辅助空间,然后将原字符串逆向拷贝到辅助空间,然后输出;
另一种是原地逆序,不需要额外的辅助空间,方法就是字符串首尾交换。
#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\n", 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\n",s ); return 0; }
from: https://www.cnblogs.com/lvonve/
相关推荐
stulen 2020-08-15
fengzhiwu 2020-08-01
xiaobaif 2020-06-14
lemonzhangyan 2020-06-13
Crazyshark 2020-06-13
weikaixxxxxx 2020-06-13
有梦就能实现 2020-06-10
shengnanonly 2020-06-03
oraclemch 2020-05-30
poplpsure 2020-05-27
zuihaobushi 2020-04-30
luckymaoyy 2020-04-29
AaronPlay 2020-06-13
文山羊 2020-10-20
Tristahong 2020-10-14
xiaoseyihe 2020-08-11
amberom 2020-08-03
pythonxuexi 2020-07-30
leoaran 2020-07-21