C語言交換字串範例

2019-10-16 22:09:23

在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

注意:上面範例中只是交換兩個相同長度的字元陣列變數的值。你可根據自己的理解開發更複雜的功能:如兩個不同長度的字串怎麼交換?