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

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

  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. }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值