在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
注意:上面示例中只是交換兩個相同長度的字元數組變數的值。你可根據自己的理解開發更複雜的功能:如兩個不同長度的字串怎麼交換?