目录
strlen
模拟实现
strcpy
模拟实现
strcat
模拟实现
strcmp
模拟实现
strncpy
strncat
strncmp
strstr
模拟实现
size_t strlen (const char * str)
字符串将'\0'作为结束标志,strlen函数返回的是在字符串中'\0'前面出现的字符个数(不包含'\0').
参数指向的字符串必须要以'\0'结束。
函数的返回值为size_t,是无符号的(unsigned int)
这里用strlen(str2) - strlen(str1)的值来判断字符串长度大小。明明str2只有三个字符,但是结果显示的是str2>str1。这里就是因为strlen返回的值都是size_t(无符号整形),两个无符号整形相减得到的结果也是无符号整形,结果本应该是-3,却因为是无符号整形改变了它的值,变成一个无穷大的数。这就是为什么输出结果是str2 > str1.简单的解决方法是在前面强制类型转换成int即可。
char* strcpy(char * destination, const char * source)
Copies the C string pointed by source into the array pointed by destination, including the terminating null character(and stopping at that point)
源字符串必须以'\0'结束。
会将源字符串中的'\0'拷贝到目标空间。
目标空间必须足够大,以确保能存放源字符串。
目标空间必须可变。
char * strcat ( char * destination, const char * source)
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.
源字符串必须以'\0'结束。
目标空间必须足够大,能容纳下源字符串的内容。
目标空间必须可修改。
int strcmp( const char * str1,const char * str2)
This function starts comparing the first character of each string. If they r equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
标准规定:
第一个字符串大于达尔戈字符串,则返回大于0的数字。
第一个字符串等于第二个字符串,则返回0
第一个字符串小于第二个字符串,则返回小于0的数字
char * strncpy( char * destination, const char * source, size_t num)
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
拷贝num个字符从源字符串到目标空间
如果源字符串的长度小于num,则拷贝完源字符串之后,在目标后面追加‘\0’,直到num个。
char * strncat( char * destination, const char * source, size_t num)
Appends the first num characters of source to destination, plus a terminating null-character.
追加完毕后后在末尾添加'\0'
If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.
如果num大于source string长度,不会额外追加。
int strncmp( const char *string1, const char *string2, size_t count)
比较到出现另个字符不一样或者一个字符串结束或者num个字符全部比较完。
大体与strcmp相似,也是在末尾添加一个num,限制了比较数量。
char * strstr( const char * string, const char *strCharSet)
Return Value
Each of these functions returns a pointer to the first occurrence of strCharSet in string, or NULL if strCharSet does not appear in string.If strCharSet points to a string of zero length, the function returns string.
返回的是在string中首次出现strCharSet字符串的地址。如果没有在string中找到strCharSet字符串,返回NULL。或者strCharSet字符串的长度为0,函数返回string。