C语言中怎样交换两个字符串

Python012

C语言中怎样交换两个字符串,第1张

不同的情况做法是不同的。

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

}

它与简单变量的交换方法相同,但是字符串的传递是通过系统函数实现的。例如: \x0d\x0achar str1[20]={"beijing"},str2[20]={"qindao"}, temp[20]\x0d\x0astrcpy(str1,temp) strcpy(str2,str1)strcpy(temp,str2)\x0d\x0astrcpy 函数功能是字符串复制,将第一个参数指定的字符串复制到第二个参数指定的位置 \x0d\x0a两个参数都是字符串首地址。 \x0d\x0a使用strcpy需要 #include \x0d\x0a希望能帮助你!

C语言中交换两个字符串需要借助strcpy函数或者使用自定义交换函数进行交换

如交换a,b数组中的字符串代码:

char a[10] = "abed", b[10] = "efg", t[10]strcpy(t, a)//a复制给tstrcpy(a, b)//b复制给astrcpy(b, t)//t复制给b

附:strcpy函数详情

原型声明:

char *strcpy(char* dest, const char *src)

头文件:

#include <string.h>和 #include <stdio.h>

功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间

说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。返回指向dest的指针。