1.模拟实现strlen
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
int MyStrlen(const char *str)
{
assert(str != NULL);
int count = 0;
while (*str)
{
count++;
str++;
}
return count;
}
int main()
{
char str[] = "hello tomorrow";
int count = MyStrlen(str);
printf("%d", count);
return 0;
}
2、模拟实现strcpy
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
void MyStrcpy(char* dest, const char* sor)
{
assert(dest != NULL && sor != NULL);
while (*sor)
{
*dest = *sor;
sor++;
dest++;
}
}
int main()
{
char sor[] = "hello tomorrow";
char dest[50] = { 0 };
MyStrcpy(dest, sor);
printf("%s", dest);
return 0;
}
3、模拟实现strcmp
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
char * MyStrcpy(char* dest, const char* sor)
{
assert(dest != NULL && sor != NULL);
char *p = dest;
while (*sor)
{
*dest = *sor;
sor++;
dest++;
}
return p;
}
int main()
{
char sor[] = "hello tomorrow";
char dest[50] = { 0 };
char* a = MyStrcpy(dest, sor);
printf("%s", a);
return 0;
}
4、模拟实现strcat
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
char* MyStrcat(char* dest, const char* src)
{
assert(*src && *dest);
char* p = dest;
while (*dest)
{
dest++;
}
while (*src)
{
*dest = *src;
src++;
dest++;
}
return p;
}
int main()
{
char* src = "hello tomorrow\n";
char dest[50] = "hello today\n";
char* a = MyStrcat(dest, src);
printf("%s", a);
return 0;
}
5、模拟实现strstr
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<assert.h>
char* MyStrstr(char *hay, char *ned)
{
assert(*hay && *ned);
char* i = hay;
char* j = ned;
while (*hay)
{
while (*hay == *ned)
{
hay++;
ned++;
if (*ned == '\0')
{
return i;
}
}
ned = j;
hay++;
i = hay;
}
return 0;
}
int main()
{
char *hay = "abcaabcde";
char *ned = "ca";
char* a = MyStrstr(hay, ned);
printf("%s", a);
return 0;
}
6、模拟实现memcpy
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
void *MyMemcpy(void *dest, void *src, int count)
{
void *ret = dest;
while (count != 0)
{
*(char*)dest = *(char*)src;
((char*)dest)++;
((char*)src)++;
count--;
}
return ret;
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int arr2[8] = { 0 };
MyMemcpy(arr2, arr1, 16);
for (int i = 0; i < 8; i++)
{
printf("%d", arr2[i]);
}
return 0;
}
7、模拟实现memmove
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void* MyMemove(void* dest, void* src, int count)
{
void *ret = dest;
if (src > dest)
{
while (count != 0)
{
*(char*)dest = *(char*)src;
((char*)dest)++;
((char*)src)++;
count--;
}
}
else
{
count--;
while (count >= 0)
{
*((char*)dest + count) = *((char*)src + count);
count--;
}
}
return ret;
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int arr2[8] = { 0 };
MyMemove(arr2, arr1, 16);
for (int i = 0; i < 8; i++)
{
printf("%d", arr2[i]);
}
}