反转字符串

#include "stdafx.h" #include <string.h> //解法1 char *strrev1(const char* str) { int len = strlen(str); char *tmp = new char[len + 1]; strcpy(tmp,str); for (int i = 0; i < len/2; ++i) { char c = tmp[i]; tmp[i] = tmp[len - i - 1]; tmp[len - i -1] = c; } return tmp; } //解法2 char *strrev2(const char *str) { char *tmp = new char[strlen(str) + 1]; strcpy(tmp, str); char *p = tmp + strlen(str) - 1; char *ret = tmp; while(p > tmp) { char t = *tmp; *tmp = *p; *p = t; --p; ++tmp; } return ret; } //解法3 char *strrev3(const char *str) { char *tmp = new char[strlen(str) + 1]; strcpy(tmp, str); char *ret = tmp; char *p = tmp + strlen(str) - 1; while (p > tmp) { *p ^= *tmp; *tmp ^= *p; *p ^= *tmp; --p; ++tmp; } return ret; } //解法4 char *strrev4(const char* str) { char *tmp = new char[strlen(str) + 1]; strcpy(tmp, str); char *ret = tmp; char *p = tmp + strlen(str) - 1; while(p > tmp) { *p = *p + *tmp; *tmp = *p - *tmp; *p = *p - *tmp; --p; ++tmp; } return ret; } //解法5 char *strrev5(char *str, int len) { if (len <= 1) return str; char t = *str; *str = *(str + len -1); *(str + len - 1) = t; return (strrev5(str+1,len-2) - 1); } int main(int argc, char* argv[]) { char str[] = "hello";//改成char *str = "hello";就有问题 printf("%s/n",str); char *str2 = strrev1(str); printf("%s/n",str2); char *str3 = strrev2(str); printf("%s/n",str3); char *str4 = strrev3(str); printf("%s/n", str4); char *str5 = strrev4(str); printf("%s/n",str5); char *str6 = strrev5(str,strlen(str)); printf("%s/n", str6); return 0; }

参考来源:http://k-eckel.cnblogs.com/articles/195931.html

你可能感兴趣的:(c,include)