ITeye博客

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

dhj · 2008-10-10 10:37 · c&c++ · Markdown

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

  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)

暂无评论。

评论功能维护中,当前仅展示历史评论。