C語言模擬實現【strncpy】 【strncat】 【strncmp】
阿新 • • 發佈:2018-11-15
模擬實現【strncpy】
char *my_strncpy(char* dest,char *src,size_t count)
{
char *ret = dest;
assert(dest);
assert(src);
while(count)
{
*dest++ = *src++; //每拷貝一個,count--,拷貝count次
count--;
}
return ret;
}
int main()
{
char arr1[20] = {0};
char arr2[] = "abcdefg" ;
printf("%s\n",my_strncpy(arr1,arr2,5));
system("pause");
return 0;
}
模擬實現 【strncat】
char *my_strncat(char*dest, char *src,size_t count)
{
char *tmp = dest;
int i =0;
assert(dest!= NULL);
assert(src != NULL);
while(*dest) //當dest = '\0'時,跳出while迴圈,因為實在'\0'後面追加。
{
dest++;
}
for (i=0;i<count;i++)//迴圈count次,追加count個字元。
{
*dest++ = *src++;
}
return tmp;
}
int main()
{
char arr[20] = "hello ";//必須有足夠大的空間
printf("%s\n",my_strncat(arr,"worlddd",5));
system("pause");
return 0;
}
模擬實現【strncmp】
int *my_strncmp(const char*str1,const char *str2,size_t num)
{
assert (str1!= NULL);
assert(str2!= NULL);
while (*str1 == *str2 && num)//兩個字元相等,並且比較的個數不為零,繼續比較
{
if (str1 == '\0')//一個字串到最後一個字元,比較完畢,
{
return 0;
}
str1++;
str2++;
num--;
}
return *str1 - *str2;
}
int main()
{
char str1[] = "abcdefgi";
char str2[] = "abcdefhk";
printf("%d",my_strncmp(str1,str2,3));
system("pause");
return 0;
}