#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
方法一:创建临时变量计数器
int my_strlen(char *s)
{
int count=0;
while (*s != '\0'){
count++;
s++;
}
return count;
}
//方法二:利用递归的方式
int my_strlen(char *str){
if (*str == '\0')
return 0;
else
return(1 + my_strlen(str + 1));
}
//方法三:利用指针减指针的方式
int my_strlen(char *s)
{
char *p = s;
while (p != '\0'){
p++;
}
return (p - s);
}
int main(){
char *str = "abc123";
int ret = my_strlen(str);
printf("%d\n ", ret);
system("pause");
return 0;
}
//模拟实现strcpy
char my_strcpy(char *dest, char *src)
{
char* ret = dest;
assert(dest != NULL);
assert(src != NULL);
while ((*dest++ = *src++)){
;
}
return ret;
}
int main()
{
const char* src = "abcd1234";
char dst[20];
my_strcpy(dst, src);
printf("%s ", dst);
system("pause");
return 0;
}
//模拟实现strcat函数
char my_strcat(char* dest, const char* src)
{
char *ret = dest;
assert(dest);
assert(src);
while (*dest){
dest++;
}
while ((*dest++ = *src++))
{
;
}
return ret;
}
int main()
{
const char*src = "abcd1234";
char dst[20] = "xyz";
my_strcat(dst, src);
printf("%s", dst);
system("pause");
return 0;
}
//模拟实现strstr函数
char my_strstr(const char*str, const char*sub_str)
{
assert(str);
assert(sub_str);
char *str_begin = str;
char *p = str_begin;
char *q = sub_str;
while (*str_begin){
p = str_begin;
q = sub_str;
while (*p!='\0'&&*q!='\0'&&*p == *q){
p++;
q++;
}
if (*q == '\0'){
return str_begin;
}
if (*p == '\0')
{
return NULL ;
}
str_begin++;
}
}
int main()
{
const char *str = "abc1234abcdef";
const char*sub_str = "abcd";
char ret=my_strstr(str, sub_str);
if (ret)
{
printf("%s\n ", ret);
}
else
printf("没有找到!");
system("pause");
return 0;
}