1,strncpy
char * strncpy(char *destination,const char *source,size_t num)
将src空间拷贝num的长度字符串到dest空间,如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后面追加0,直到num个。src和dest所指的内存区域不能重叠,且dest必须有足够的空间放置n个字符。 strncpy的自实现:他的原理无非就是通过指针拷贝赋值,拷贝时dest会移动,而最终要返回的是拷贝后字符串的起始地址,因此要先保存dest的地址,便于最终返回。
char* my_strncpy(char *destination,const char *source,size_t num)
{
assert(*destination!=NULL&&*source!=NULL);
char *dest = destination;
while (*destination!='\0'&&num>0)
{
*destination++ = *source++;
num--;
}
while (num>0)
{
*destination = '\0';
num--;
}
return dest;
}
2,strncat
char *strncat(char *destination,const char *source,size_t num)
函数功能:把source所指字符串的前n个字符添加到destination结尾处,覆盖destination结尾处的'/0',实现字符串连接。源字符串和目的字符串所指内存区域不可以重叠,并且目的字符串必须有足够的空间来容纳的源符串。 strncat的自实现:首先断言源字符串和目的字符串不为空,找到目的字符串的‘\0’的位置,然后将所需n个源字符串的地址赋值给目的字符串。
char *my_strncat(char *destination,const char*source,size_t num)
{
assert(*destination != NULL&&*source != NULL);
char *dest = destination;
while (*destination)
{
destination++;
}
while (num > 0)
{
*destination++ = *source++;
num--;
}
*destination = '\0';
return dest;
}
3,strcmp
字符串比较函数,他的规定就是第一个字符串大于第二个字符串,则返回大于0的数字,第一个字符串等于第二个字符串,则返回0,第一个字符串小于第二个字符串,则返回小于0的数字。
int strcmp(const char *str1,const char *str2)
strcmp的自实现:用减法,所该字母所减出来的结果如果不等于零,说明判断出来了结果,直接返回。
int my_strcmp(const char *str1,const char *str2)
{
assert(*str1 != NULL&&*str2 != NULL);
int ret = 0;
while (*str1 != '\0' || *str2 != '\0')
{
ret = *str1 - *str2;
if (ret!=0)
{
break;
}
str1++;
str2++;
}
return ret;
}
4,strncmp
strncmp函数首先将str1字符串的第一个字符的ACSII值减去str2第一个字符的ACSII值(自左向右比较前n个字符,直到出现不同的字符或遇'\0'为止)
strncmp的自实现:在strncmp的基础上加了一个长度限制条件,若len==0返回0。
int my_strncmp(const char *str1, const char *str2, size_t len)
{
assert(*str1 != NULL&&*str2 != NULL);
while (*str1 !='\0' && *str2!='\0'&& *str1==*str2&&len>0)
{
str1++; str2++; len--;
}
if (len == 0) { return 0; }
return (*str1 - *str2);
}