C語言字串拷貝範例

2019-10-16 22:09:19

在C語言中,如何拷貝字串?建立一個原始檔:program_to_copy_string.c,參考以下實現程式碼 -

#include <stdio.h>

int main() {
    char s1[] = "tw511.com";       // String Given
    char s2[18];                   // Variable to hold value

    int length = 0;

    while (s1[length] != '\0') {
        s2[length] = s1[length];
        length++;
    }

    s2[length] = '\0';           // Terminate the string

    printf("Value in s1 = %s \n", s1);
    printf("Value in s2 = %s \n", s2);

    return 0;
}

執行上面範例程式碼,得到以下結果 -

Value in s1 = tw511.com
Value in s2 = tw511.com