#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; }