[C] 實作strcpy, strncpy, strcmp

Samuel Liu
Sep 26, 2021

--

strcpy:

char* strcpy(char* des, const char* src){
if(des == NULL || src == NULL)
return NULL;
while(*src != '\0'){
*des = *src;
des++;
src++;
}
*des = '\0';
return des;
}

strncpy:

char* strncpy(char* des, const char* src, unsigned count){
if(des == NULL || src == NULL)
return NULL;
while(count > 0){
*des = *src;
des++;
src++;
count--;
}
*des = '\0';
return des;
}

strcmp:

int strcmp(const char* a, const char* b){
if(a == NULL || b == NULL)
return 0;
while(*a == *b){
if(*a == '\0')
return 0;
a++;
b++;
}
return *a - *b;
}

--

--