---
title: " c++指针学习笔记--交换两个字符串数据"
author: "dhj"
date: "2008-10-10T10:37:34Z"
tags: []
slug: "c"
draft: false
lastmod: "2008-10-10T10:37:34Z"
id: 251113
url: "https://dang.iteye.com/blog/251113"
---

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

01. int  main()
02. {
03. void  charsort2( char  \** , char  \*\*);
04. char  * s1= "abc" ;
05. char  * s2= "baihe" ;
06. charsort2 (&s1,&s2);
07. cout&lt;&lt;s1&lt;&lt;endl;
08. cout&lt;&lt;s2&lt;&lt;endl;
09. return  0;
10. }
11. void  charsort2( char  \*\*s1, char  \*\*s2)
12. {
13. char  \*p;
14. p=\*s1;
15. \*s1=\*s2;
16. \*s2=p;
17. }

二：字符数组

01. int  main()
02. {
03. void  charsort(  char  * , char  * );
04. char  s1\[7]= "abc" ;
05. char  s2\[7]= "baihe" ;
06. charsort(s1,s2);
07. cout&lt;&lt;s1&lt;&lt;endl;
08. cout&lt;&lt;s2&lt;&lt;endl;
09. 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. }

三：字符串

01. int  main()
02. {
03. void  strsort( string  \*, string  \*);
04. string  s1= "abc" ;
05. string  s2= "baihe" ;
06. strsort(&s1,&s2);
07. cout&lt;&lt;s1&lt;&lt;endl;
08. cout&lt;&lt;s2&lt;&lt;endl;
09. return  0;
10. }
11. void  strsort( string  \*s1, string  \*s2)
12. {
13. string  p;
14. p=\*s1;
15. \*s1=\*s2;
16. \*s2=p;
17. }

四：引用

01. int  main()
02. {
03. void  strsort( string  &, string  &);
04. string  s1= "abc" ;
05. string  s2= "baihe" ;
06. strsort(s1,s2);
07. cout&lt;&lt;s1&lt;&lt;endl;
08. cout&lt;&lt;s2&lt;&lt;endl;
09. return  0;
10. }
11. void  strsort( string  & s1, string  &s2)
12. {
13. string  p;
14. p=s1;
15. s1=s2;
16. s2=p;
17. }

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

五:指针引用:

01. int  main()
02. {
03. void  charsort2( char \*& , char \*&);
04. char  * s1= "abc" ;
05. char  * s2= "baihe" ;
06. charsort2 (s1,s2);
07. cout&lt;&lt;s1&lt;&lt;endl;
08. cout&lt;&lt;s2&lt;&lt;endl;
09. return  0;
10. }
11. void  charsort2( char  \*&s1, char  \*&s2)
12. {
13. char  \*p;
14. p=s1;
15. s1=s2;
16. s2=p;
17. }