[simulate strncpy], [simulate strncat], [simulate strncmp]
All three functions are implemented in bytes
[strncpy]
char* strncpy(char* destination,const char* source,size_t num);
Copy num characters from the source character to the target space. If the length of the source string is less than num, add 0 to the back of the target after the source string is tested, until num characters.
char* my_strncpy(char* dest, const char*src, size_t num)
{
char* ret = dest;
assert(dest);//Detect whether dest exists, not NULL
assert(src);
while (num)
{
*dest++ = *src++;//One byte one byte copy
num--;
if ((*src == '\0') && (num <= 0))//If the source string bytes are less than num, add enough num after the target string
{
*dest++ = '\0';
return ret;//Return target string
}
}
return ret;
}
[strncat]
char* strncat(char* destination,const char* source,size_t num);
Splice the num characters of the source string to the target string. When splicing the string, it will add '\ 0' to you by default.
char* my_strncat(char* dest, const char* src, size_t num)
{
char* ret = dest;
assert(dest);//Detect whether dest exists, not NULL
assert(src);
while (*dest)
{
dest++;//Find the end of the target string first
}
while (num)
{
*dest++ = *src++;//Start splicing one by one from the end back
num--;
}
*dest++ = '\0';//After splicing, add '\ 0' after the target string
return ret;//Return target string
}
[strncmp]
int strncmp(const char* str1,const char* str2,size_t num);
Compare two strings by byte, and find that there are different characters, or one string ends or num characters are all compared.
int my_strncmp(const char* str1, const char* str2, size_t num)
{
assert(str1);//Detect whether dest exists, not NULLw
assert(str2);
int ret = 0;
while (num)//Compare num times
{
ret = *(unsigned char*)str1 - *(unsigned char*)str2;
str1++;
str2++;
if (ret < 0)
ret = -1;
else if (ret>0)
ret = 1;
if (!*str1 || !*str2)
ret = 0;
}
return ret;
}
The Works of Liezi:
//As you can see, this function is to find out the string starting with A4 in six strings
int test()
{
char str[][6] = { "A499", "BF77", "3456", "A401", "A4HJ", "B612" };
int n;
puts("Looking for A4 ...\n");
for (n = 0; n < 6; n++)
{
if (strncmp(str[n], "A4xx", 2) == 0)//Print when you find it
printf("%s\n", str[n]);
}
return 0;
}
If there is something wrong, you can comment and tell me, hope to guide!