c++指针学习笔记--交换两个字符串数据

来源:互联网 发布:win7查找网络打印机 编辑:程序博客网 时间:2024/04/29 05:21

交换两个字符串数据。
一:字符指针

  1. int main()
  2. {
  3.     void charsort2(char ** ,char **);
  4.         char * s1="abc";
  5.     char * s2="baihe";  
  6.     charsort2 (&s1,&s2);
  7.     cout<<s1<<endl;
  8.     cout<<s2<<endl;    
  9.     return 0;   
  10. }
  11. void charsort2(char **s1,char **s2)
  12. {
  13.     char *p;
  14.     p=*s1;
  15.     *s1=*s2;
  16.     *s2=p;
  17. }

二:字符数组

  1. int main()
  2. {
  3.     void charsort( char * ,char * );
  4.         char s1[7]="abc";
  5.     char s2[7]="baihe"
  6.     charsort(s1,s2);
  7.     cout<<s1<<endl;
  8.     cout<<s2<<endl; 
  9.     return 0;   
  10. }
  11. void charsort(char *s1,char *s2)
  12. {
  13.     char p[7];
  14.     strcpy(p,s1);
  15.     strcpy(s1,s2);
  16.     strcpy(s2,p);   
  17. }

三:字符串

  1. int main()
  2. {
  3.     void strsort(string *,string *);
  4.         string s1="abc";
  5.     string s2="baihe";  
  6.     strsort(&s1,&s2);
  7.     cout<<s1<<endl;
  8.     cout<<s2<<endl;    
  9.     return 0;   
  10. }
  11. void strsort(string *s1,string *s2)
  12. {
  13.     string p;
  14.     p=*s1;
  15.         *s1=*s2;
  16.     *s2=p;
  17. }

四:引用

  1. int main()
  2. {
  3.     void strsort(string &,string &);
  4.         string s1="abc";
  5.     string s2="baihe";  
  6.     strsort(s1,s2);
  7.     cout<<s1<<endl;
  8.     cout<<s2<<endl;    
  9.     return 0;   
  10. }
  11. void strsort(string & s1,string &s2)
  12. {
  13.     string p;
  14.     p=s1;
  15.     s1=s2;
  16.     s2=p;
  17. }

多谢论坛上朋友的分享.以下为新添方法:

五:指针引用:

  1. int main()
  2. {
  3.     void charsort2(char*& ,char*&);
  4.     char * s1="abc";
  5.     char * s2="baihe";    
  6.     charsort2 (s1,s2);
  7.     cout<<s1<<endl;
  8.     cout<<s2<<endl;    
  9.     return 0;    
  10. }
  11. void charsort2(char *&s1,char *&s2)
  12. {
  13.     char *p;
  14.     p=s1;
  15.     s1=s2;
  16.     s2=p;
  17. }
原创粉丝点击