交换两个字符串数据。
一:字符指针
- int main()
- {
- void charsort2( char ** , char **);
- char * s1= "abc" ;
- char * s2= "baihe" ;
- charsort2 (&s1,&s2);
- cout<<s1<<endl;
- cout<<s2<<endl;
- return 0;
- }
- void charsort2( char **s1, char **s2)
- {
- char *p;
- p=*s1;
- *s1=*s2;
- *s2=p;
- }
二:字符数组
- int main()
- {
- void charsort( char * , char * );
- char s1[7]= "abc" ;
- char s2[7]= "baihe" ;
- charsort(s1,s2);
- cout<<s1<<endl;
- cout<<s2<<endl;
- return 0;
- }
- void charsort( char *s1, char *s2)
- {
- char p[7];
- strcpy(p,s1);
- strcpy(s1,s2);
- strcpy(s2,p);
- }
三:字符串
- int main()
- {
- void strsort( string *, string *);
- string s1= "abc" ;
- string s2= "baihe" ;
- strsort(&s1,&s2);
- cout<<s1<<endl;
- cout<<s2<<endl;
- return 0;
- }
- void strsort( string *s1, string *s2)
- {
- string p;
- p=*s1;
- *s1=*s2;
- *s2=p;
- }
四:引用
- int main()
- {
- void strsort( string &, string &);
- string s1= "abc" ;
- string s2= "baihe" ;
- strsort(s1,s2);
- cout<<s1<<endl;
- cout<<s2<<endl;
- return 0;
- }
- void strsort( string & s1, string &s2)
- {
- string p;
- p=s1;
- s1=s2;
- s2=p;
- }
多谢论坛上朋友的分享.以下为新添方法:
五:指针引用:
- int main()
- {
- void charsort2( char *& , char *&);
- char * s1= "abc" ;
- char * s2= "baihe" ;
- charsort2 (s1,s2);
- cout<<s1<<endl;
- cout<<s2<<endl;
- return 0;
- }
- void charsort2( char *&s1, char *&s2)
- {
- char *p;
- p=s1;
- s1=s2;
- s2=p;
- }