1. strlen的使用 & 模拟实现
size_t strlen ( const char * str );
• 字符串以 '\0' 作为结束标志,strlen函数返回的是在字符串中 '\0' 前面出现的字符个数(不包 含 '\0' )。
• 参数指向的字符串必须要以 '\0' 结束。
• 注意函数的返回值为size_t,是无符号的( 易错 )
• strlen的使用需要包含头文件
• 学会strlen函数的模拟实现
#include <stdio.h>
#include <string.h>
int main()
{const char* str1 = "abcdef";const char* str2 = "bbb";if(strlen(str2)-strlen(str1)>0){printf("str2>str1\n");} else{printf("srt1>str2\n");}return 0;
}
strlen的模拟实现:
方式1:
//计数器⽅式
int my_strlen(const char * str)
{int count = 0;assert(str);while(*str){count++;str++;}return count;
}
方式2:
//不能创建临时变量计数器
int my_strlen(const char * str)
{assert(str);if(*str == '\0')return 0;elsereturn 1+my_strlen(str+1);
}
方式3:
//指针-指针的⽅式
int my_strlen(char *s)
{assert(str);char *p = s;while(*p != ‘\0’ )p++;return p-s;
}
2. strcpy的使用 & 模拟实现
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' 拷贝到目标空间。
• 目标空间必须足够大,以确保能存放源字符串。
• 目标空间必须可修改。
• 学会模拟实现。
strcpy的模拟实现:
//1.参数顺序
//2.函数的功能,停⽌条件
//3.assert
//4.const修饰指针
//5.函数返回值
//6.题⽬出⾃《⾼质量C/C++编程》书籍最后的试题部分
char *my_strcpy(char *dest, const char*src)
{ char *ret = dest;assert(dest != NULL);assert(src != NULL);while((*dest++ = *src++)){;}return ret;
}
3. strcat的使用 & 模拟实现
• 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' 结束。
• 目标字符串中也得有 \0 ,否则没办法知道追加从哪里开始。
• 目标空间必须有足够的大,能容纳下源字符串的内容。
• 目标空间必须可修改。
• 字符串自己给自己追加,如何?
模拟实现strcat函数:
char *my_strcat(char *dest, const char*src)
{char *ret = dest;assert(dest != NULL);assert(src != NULL);while(*dest){dest++;}while((*dest++ = *src++)){;}return ret;
}
4. strcmp的使用 & 模拟实现
• This function starts comparing the first character of each string. If they are 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的数字
◦ 那么如何判断两个字符串? 比较两个字符串中对应位置上字符ASCII码值的大小。
strcmp函数的模拟实现:
int my_strcmp (const char * str1, const char * str2)
{int ret = 0 ;assert(src != NULL);assert(dest != NULL);while(*str1 == *str2){if(*str1 == '\0')return 0;str1++;str2++;}return *str1-*str2;
}