最普通的方法:
char *reverse_0(char *s) { char *q = s; while(*q++); q = q-2; char *p = new char[sizeof(char)*(q-s+2)]; //为逆序后的字符串分配存储空间 char *r = p; while( q>=s ) *p++ = *q--; *p = '\0'; return r; }一、设置两个指针,分别指向字符串的头部和尾部,然后交换两个指针所指的字符,并向中间移动指针直到相交。代码如下: char *reverse_1(char *s) { char *p =s; char *q=s; while(*q) //q指向字符串尾部 ++q; q--; //q指向字符串最后一个字符 while( q > p ) //指针的大小比较,比的是所指向的字符在字符串中的位置的关系 { char t = *p; *p++ = *q; *q-- = t; } return s; }二、使用字符串结束符'\0'所在的位置作为交换空间 --- 不使用临时变量的原地逆序 char *reverse_2(char* s) { char *r = s; char* p = s; while(*p != '\0') //使p指向字符串最后的'\0' ++p; char* q = p -1; //使q指向字符的最后一个字符 while(q>s) { *p = *q; //利用最后的'\0'作为交换空间 *q-- = *s; *s++ = *p; } *p = '\0'; //恢复最后的'\0' return r; }三、使用异或操作 -- 不使用临时变量 char* reverse_3(char* s) { char* r = s; char* p = s; while(*(p+1)!='\0') ++p; while(p>s) { *p = *p ^ *s; *s = *p ^ *s; *p = *p-- ^ *s++; } return r; } 关于怎么使用异或操作交换两个数、字符。调试代码 #include <iostream> using namespace std; char *reverse(char *s) { char *p = s; char *q = s; while(*q) ++q; q--; cout<<"*q="<<*q<<endl; while(q > p) { cout<<q<<endl<<p<<endl; char t = *p; *p++ = *q; *q-- = t; } return s; } char *reverse_2(char *s) { char *q = s; while(*q++); q = q-2; char *p = new char[sizeof(char)*(q-s+2)]; char *r = p; while( q>=s ) *p++ = *q--; *p = '\0'; return r; } char* reverse_3(char* s) { char* r = s; char* p = s; while(*(p+1)!='\0') ++p; while(p>s) { cout<<"*p = "<<*p<<" "<<"*s= "<<*s<<endl; *p = *p ^ *s; cout<<"*p = *p^*s = "<<*p<<endl; *s = *p ^ *s; cout<<"*s = *p^*s = "<<*s<<endl; *p = *p-- ^ *s++; cout<<"*p = *p-- ^ *s++ = "<<*p<<endl<<endl; } return r; } int main(int argc, char* argv[]) { int length = 0; char str[] = "abcdef"; char *dest_str; char *dest_str2; cout<<sizeof(str)<<endl; length = sizeof(str); //地址:http://www.software8.co/wzjs/cpp/4860.html 转载注明 cout<<endl<<endl<<"reverse"<<endl; dest_str = reverse(str); cout<<dest_str<<endl<<endl<<endl<<"reverse_2"<<endl; dest_str2 = reverse_2(dest_str); cout<<"dest_str2:"<<dest_str2<<endl; cout<<endl<<endl<<endl<<endl<<"reverse_3"<<endl; dest_str = reverse_3(dest_str2); cout<<dest_str2<<endl; return 0; }