搜尋此網誌

[C/C++][實作strcpy與strncpy]

/*
* Author: MH
* Since 2013/10/28
* Toolkit: Code::Block 12.11
*/

#include <stdio.h>

char *strcpy_implementation(char *strDst, const char *strSrc) {

    char *newStr = NULL;
    int strCount = 0;

    if ((strDst==NULL) || (strSrc==NULL)) {
        return NULL;
    }

    newStr = strDst;
    while (*(strSrc+strCount)!='\0') {
        *newStr = *(strSrc+strCount);
        newStr++;
        strCount++;
    }
    *newStr = '\0';

    return strDst;
}

int main () {

    char *str1 = "Sample string";
    char str2[20];

    strcpy_implementation (str2, str1);
    printf ("str1: %s\n", str1);
    printf ("str2: %s\n", str2);    // str2: Sample string

    return 0;
}

網路上還有看到比較簡潔的寫法
/*
* Author: MH
* Since 2013/10/28
* Toolkit: Code::Block 12.11
*/

#include <stdio.h>

void strcpy_implementation2 (char x[], char y[]) {
    int i = 0;
    while ((x[i]=y[i])!='\0') {
        i+=1;
    }
}

int main () {

    char *str1 = "Sample string";
    char str2[20];

    strcpy_implementation2 (str2, str1);
    printf ("str1: %s\n", str1);
    printf ("str2: %s\n", str2);    // str2: Sample string

    return 0;
}

/*
* Author: MH
* Since 2013/10/28
* Toolkit: Code::Block 12.11
*/

#include <stdio.h>

char *strncpy_implementation(char *strDst, const char *strSrc, int strLength) {

    char *newStr = NULL;
    int strCount = 0;

    if ((strDst==NULL) || (strSrc==NULL)) {
        return NULL;
    }

    newStr = strDst;
    while ((*(strSrc+strCount)!='\0') && (strCount<strLength)) {
        *newStr = *(strSrc+strCount);
        newStr++;
        strCount++;
    }
    *newStr = '\0';

    return strDst;
}

int main () {

    char *str1 = "Sample string";
    char str2[20];

    strncpy_implementation (str2, str1, 4);
    printf ("str1: %s\n", str1);
    printf ("str2: %s\n", str2);    // str2: Samp

    return 0;
}

沒有留言:

張貼留言