#include <stdio.h> #include <stdlib.h> #include <assert.h> void strrev_v1(char* src) { assert(src != NULL); if (strlen(src) == 1) return; char *head = src; char *tail = src + strlen(src) - 1; char temp = ' '; while(head < tail) { temp = head[0]; head[0] = tail[0]; tail[0] = temp; head++; tail--; } } void strrev_v2(char* src) { assert(src != NULL); if (strlen(src) == 1) return; char *head = src; char *tail = src + strlen(src) - 1; while(head < tail) { head[0] ^= tail[0]; tail[0] ^= head[0]; head[0] ^= tail[0]; head++; tail--; } } void strrev_v3(char* src) { assert(src != NULL); if (strlen(src) == 1) return; char *head = src; char *tail = src + strlen(src) - 1; while(head < tail) { head[0] = head[0] + tail[0]; tail[0] = head[0] - tail[0]; head[0] = head[0] - tail[0]; head++; tail--; } } void strrev_v4(char* src, int len) { //采用的是递归的思路 assert(src != NULL); if (len < 2) return; char *head = src; char *tail = src + len - 1; head[0] = head[0] + tail[0]; tail[0] = head[0] - tail[0]; head[0] = head[0] - tail[0]; strrev_v4(head+1, len-2); } int main() { char *a = (char*)malloc(5*sizeof(char)); //本来这里采用的是char *a = "12345"的写法,后来发现"12345"是常量字符串,不能被修改,当然就不能被交换了。 strcpy(a, "12345"); strrev_v4(a, strlen(a)); printf("%s/n", a); return 0; }