以下是交换字符串的示例。
#include<stdio.h> #include <string.h> int main() { char st1[] = "My 1st string"; char st2[] = "My 2nd string"; char swap; int i = 0; while(st1[i] != '\0') { swap = st1[i]; st1[i] = st2[i]; st2[i] = swap; i++; } printf("After swapping s1 : %s\n", st1); printf("After swapping s2 : %s\n", st2); return 0; }
输出结果
After swapping s1 : My 2nd string After swapping s2 : My 1st string
在上面的程序中,声明了两个char类型为st1和st2的数组,一个char变量'swap'和一个整数变量i。在循环检查st1是否不为null时,交换st1和st2的值。
char st1[] = "My 1st string"; char st2[] = "My 2nd string"; char swap; int i = 0; while(st1[i] != '\0') { swap = st1[i]; st1[i] = st2[i]; st2[i] = swap; i++; }