头文件<cstring>(或<string.h>)中有字符串倒序函数的: strrev(char *s),但如何自定义实现呢?
#include <iostream> #include <string> #include <sstream> #include <assert.h> using namespace std; char *reverse(char *s) { assert(s!=NULL); static stringstream ss; if (*s!='\0') reverse(s+1); ss<<*(s-1); return (char*)ss.str().c_str(); } char *strReverse(char *s) { assert(s!=NULL); char *t=s; while(*t) *t++; for(int i=0;i<(t-s)/2;i++){ *t=*(s+i); *(s+i)=*(s+(t-s)-i-1); //(t-s)指针减法,括号不能省 *(s+(t-s)-i-1)=*t; } *(s+(t-s))='\0'; return s; } int main(void) { string s = "123456789"; char *p = (char*)s.data(); p=strReverse(p); cout<<p<<endl; cout<<reverse(p)<<endl; return 0; } /* 测试结果: 987654321 123456789 -------------------------------- Process exited after 0.5639 seconds with return value 0 请按任意键继续. . . */
网上看到的,还有这种递归写法,稍作修改也通过测试:
#include <iostream> #include <cstring> void reverse2(char *s,int n) { if (n>1){ char p=*s; *s=*(s+n-1); *(s+n-1)=p; reverse2(s+1,n-2); } } int main() { char s[]="123456789"; reverse2(s,strlen(s)); std::cout<<s<<std::endl; char *str; std::string t="hello,world!"; str=(char*)t.c_str(); reverse2(str,strlen(str)); std::cout<<str<<std::endl; return 0; } /* 运行结果: 987654321 !dlrow,olleh -------------------------------- Process exited after 0.6639 seconds with return value 0 请按任意键继续. . . */