字符串的反转五种方法

发布时间:2016-12-7 20:29:02 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"字符串的反转五种方法",主要涉及到字符串的反转五种方法方面的内容,对于字符串的反转五种方法感兴趣的同学可以参考一下。

#include<iostream> #include<string> using namespace std; char *reverse1( char *str, int len) { if(len<=1) //边界条件 return str; char temp = *str; *str = *(str+len-1); *(str+len-1) = temp; return (reverse1( str+1, len-2)-1); } char *reverse2( const char *str) { char *temp = new char[strlen(str)+1]; strcpy(temp, str); //会复制\0 int len = strlen(str); for( int i=0; i<len/2; i++) { char ch = temp[i]; temp[i] = temp[len-i-1]; temp[len-i-1] = ch; } // temp[len] = '\0'; return temp; } char *reverse3( const char *str) { char *temp = new char[strlen(str)+1]; strcpy(temp, str); int len = strlen(str); char *head = temp; char *rear = temp+len-1; while(head<rear) { char ch = *head; *head = *rear; *rear = ch; ++head; --rear; } // temp[len] = '\0'; return temp; } char *reverse4( const char *str) { char *temp = new char[strlen(str)+1]; strcpy(temp, str); int len = strlen(str); char *head = temp; char *rear = temp+len-1; while(head<rear) { *head = *head+*rear; *rear = *head-*rear; *head = *head-*rear; ++head; --rear; } return temp; } char *reverse5( const char *str) { char *temp = new char[strlen(str)+1]; strcpy(temp, str); int len = strlen(str); char *head = temp; char *rear = temp+len-1; while(head<rear) { *head^=*rear; *rear^=*head; *head^=*rear; ++head; --rear; } return temp; } int main() { char str[7] = "123456"; cout<<reverse2(str)<<endl; cout<<reverse3(str)<<endl; cout<<reverse4(str)<<endl; cout<<reverse5(str)<<endl; cout<<reverse1(str, 6)<<endl; return 0; }

上一篇:Python自省(反射)指南
下一篇:Oracle Database 11g SQL 开发指南学习笔记:运行store_schema.sql时报错的问题

相关文章

相关评论