字符串的交换——3种实现

要知道,a[100]字符串的首地址与char *a 是不一样的,
a[100]字符串的首地址不是指针,char *a就是指针!!!
View Code
//swap(char *a,char *b)
#include<iostream>
#include
<string.h>
using namespace std;

void swap(char *a,char *b)
{
int al,bl,i;
al
=strlen(a)+1;
bl
=strlen(b)+1;
if(al<bl)al=bl;

int temp;
for(i=0;i<al;i++)
{

temp
=a[i];
a[i]
=b[i];
b[i]
=temp;
}
}

void main()
{
char ap[20]="hello!";
char bp[20]="how are you!";

swap(ap,bp);
cout
<<ap<<endl;
cout
<<bp<<endl;
}


//swap(char* *a,char* *b)
#include<iostream>
using namespace std;

void swap1(char* *a,char* *b)
{
char *temp;
temp
=*a;
*a=*b;
*b=temp;
}

void main()
{
char *ap="hello!";
char *bp="how are you!";

swap1(
&ap,&bp);
cout
<<ap<<endl;
cout
<<bp<<endl;
}

//swap(char* &a,char* &b)
#include<iostream>
using namespace std;

void swap1(char* &a,char* &b)
{
char *temp;
temp
=a;
a
=b;
b
=temp;
}

void main()
{
char *ap="hello!";
char *bp="how are you!";

swap1(ap,bp);
cout
<<ap<<endl;
cout
<<bp<<endl;
}
原文地址:https://www.cnblogs.com/huhuuu/p/1977590.html