一、模拟实现strlen
方式一
//方式一:设置计数器
int my_strlen(const char * str)
{
assert(str != NULL);
int count = 0;
while (*str)
{
str++;
count++;
}
return count;
}
方式二
//二、不能创建临时变量计数器——递归
int my_strlen(const char * str)
{
assert(str != NULL);
if (*str == '\0')
return 0;
else
return 1 + my_strlen(str + 1);
}
方式三
//三、指针 — 指针 即元素个数
int my_strlen(char *s)
{
assert(s != NULL);
char *p = s;
while (*p != '\0')
{
p++;
}
return p - s;
}
main函数
int main()
{
char str[] = "abcdef";
printf(" %d \n", my_strlen(str));//6
system("pause");
return 0;
}
二、模拟实现strcpy
char *my_strcpy(char *target, const char *source)
{
char *start = target;
assert(target != NULL);
assert(source != NULL);
while (*target++ = *source++)
{
;
}
return start;
}
int main()
{
char str1[10] = "0";//防止越界产生
char str2[15] = "abcdef";
printf("str1: %s \n", my_strcpy(str1, str2));
system("pause");
return 0;
}
三、模拟实现strcat
char *my_strcat(char *target, const char *source)
{
char *start = target;
assert(target != NULL);
assert(source != NULL);
while (*target)
{
target++;
}
while (*target++ = *source++)
{
;
}
return start;
}
int main()
{
char str1[15] = "abcdef";
char str2[] = "ghijk";
printf("str1: %s \n", my_strcat(str1, str2));
system("pause");
return 0;
}
##四、模拟实现strstr ##
char *my_strstr(const char *str1, const char *str2)
{
assert(str1);
assert(str2);
char *cp = (char *)str1;
char *substr = (char *)str2;
char *s1 = NULL;
if (*str2 == '\0')
{
return NULL;
}
while (*cp)
{
s1 = cp;
substr = str2;
while (*s1 && *substr && (*s1 == *substr))
{
s1++;
substr++;
}
if (*substr == '\0')
{
return cp;
}
cp++;
if (*cp == '\0')
return NULL;
}
}
int main()
{
const char str1[] = "abbbcccdefgh";
const char str2[] = "ghi";
char *ret = my_strstr(str1, str2);
if (ret == NULL)
{
printf(" str2 不是 str1 的子字符串\n");
}
else
{
printf(" str2 是 atr1 的从 %d 位开始的子字符串\n",ret - str1+1);
}
system("pause");
return 0;
}
五、模拟实现strchr
char *my_strchr(const char *str, char c)
{
assert(str != NULL);
while (*str)
{
if (*(str++) == c)//对实际地址进行了后置++操作
{
return str - 1;
}
}
return NULL;
}
int main()
{
char str[] = "abcdefdgh";
char c = 'a';
char *p = my_strchr(str, c);
if (NULL == *p)
{
printf(" %s 字符串中没有 %c 字符\n",str, c);
}
else
{
printf("%c 首次出现在 %s 的位置是:%d \n",c, str, p - str + 1);
}
system("pause");
return 0;
}
六、模拟实现strcpy
int my_strcmp(const char *s1, const char *s2)
{
assert(s1 != NULL);
assert(s2 != NULL);
int ret = 0;
while (!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2)// 用!操作符控制循环,将比较换为减法得到数值正负,
{
++s1;
++s2;
}
if (ret < 0)
{
ret = -1;
}
else if (ret > 0)
{
ret = 1;
}
return ret;
}
int main()
{
char str1[] = "cd";
char str2[] = "ab";
int i = my_strcmp(str1, str2);
if (0 == i)
{
printf("str1 :%s 和 str2 :%s 相等\n",str1, str2);
}
else if (0 < i)
{
printf("str1:%s 大于 str2:%s \n",str1, str2);
}
else
{
printf("str1:%s 小于 str2:%s \n", str1, str2);
}
system("pause");
return 0;
}
小结
好东西要留到最后阐述,一步一步的深入去讲应该是一个不错的选择!