# C字符串反转算法

2016-12-14 09:54:24来源:http://blog.csdn.net/zjfei/article/details/5471065作者:zjfei人点击

void Reverse(char s[])

{

for(int i = 0, j = strlen(s) - 1; i < j; ++i, --j) {

char c = s[i];

s[i] = s[j];

s[j] = c;

}

}

#关于a, b交换其它算法：

a ^= b;

b ^= a;

a ^= b;

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;

}

char* strrev2(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)

{

char t = *tmp;

*tmp = *p;

*p = t;

--p;

++tmp;

}

return ret;

}

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;

}

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;

}

char* strrev5(/**//*const */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);

}

nt main(int argc,char* argv[])

{

char* str = "hello";

P(str);

char* str2 = strrev1(str);

P(str2);

char* str3 = strrev2(str2);

P(str3);

char* str4 = strrev3(str3);

P(str4);

char* str5 = strrev4(str4);

P(str5);

char* str6 = strrev5(str5,strlen(str5));

P(str6);

return 0;

}