在C语言中,如何交换字符串?创建一个源文件:program_to_swap_strings.c,参考以下实现代码 -
#include <stdio.h>
int main() {
char s1[] = "MyDearLe";
char s2[] = "Dazzling";
char ch;
int index = 0;
//Character by Character approach
printf("Before Swapping - \n");
printf("Value of s1 - %s \n", s1);
printf("Value of s2 - %s \n", s2);
while (s1[index] != '\0') {
ch = s1[index];
s1[index] = s2[index];
s2[index] = ch;
index++;
}
printf("After Swapping - \n");
printf("Value of s1 - %s \n", s1);
printf("Value of s2 - %s \n", s2);
return 0;
}
执行上面示例代码,得到以下结果 -
Before Swapping -
Value of s1 - MyDearLe
Value of s2 - Dazzling
After Swapping -
Value of s1 - Dazzling
Value of s2 - MyDearLe
注意:上面示例中只是交换两个相同长度的字符数组变量的值。你可根据自己的理解开发更复杂的功能:如两个不同长度的字符串怎么交换?