C语言中怎样交换两个字符串
2个回答
展开全部
不同的情况做法是不同的。
1. 如果是字符数组,char a[50]="String A"; char b[50]="String B"; 则
#include<stdio.h>
void strexchg(char *a, char *b){
char c;
while(*a && *b){
c= *a; *a = *b; *b = c;
a++; b++;
}
c= *a; *a = *b; *b = c;
if(*a)
do *++a = *++b; while(*b);
else if(*b)
do *++b = *++a; while(*a);
}
int main(){
char a[50]="String A"; char b[50]="String B";
printf("Before Exchange :\n\tString A is \"%s\"\n\tString B is \"%s\"\n",a,b);
strexchg(a,b);
printf("After Exchange :\n\tString A is \"%s\"\n\tString B is \"%s\"\n",a,b);
return 0;
}
2 如果两个都是字符指针变量,char *a="String A"; char *b="String B"; 则
#include<stdio.h>
void strexchg(char **a, char **b){
char *c;
c=*a;
*a=*b;
*b=c;
}
int main(){
char *a="String A"; char *b="String B";
printf("Before Exchange :\n\tString A is \"%s\"\n\tString B is \"%s\"\n",a,b);
strexchg(&a,&b);
printf("After Exchange :\n\tString A is \"%s\"\n\tString B is \"%s\"\n",a,b);
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询