模拟实现strcpy
#include<stdio.h>
#include<windows.h>
#include<assert.h>
size_t myStrlen(const char* str)
{
assert(str);
const char* start = str;
const char* end = str;
while (*end){
end++;
}
return end - start;
}
int main()
{
const char *str = "Hello world!";
printf("%d\n", myStrlen(str));
system("pause");
return 0;
}
模拟实现strcat
#include<stdio.h>
#include<windows.h>
#include<assert.h>
char* myStrcat(char* dst, const char* src)
{
assert(dst);
assert(src);
char* ret = dst;
while (*dst != '\0')
{
dst++;
}
while (*src != '\0')
{
*dst++ = *src++;
}
return ret;
}
int main()
{
const char *src = "Hello world!";
char dst[32];
myStrcpy(dst, src);
myStrcat(dst, src);
system("pause");
return 0;
}
模拟实现strstr
#include<stdio.h>
#include<windows.h>
#include<assert.h>
const char* myStrstr(const char* str, const char* sub)
{
assert(str);
assert(sub);
const char* str_start = str;
const char* str_p = str;
const char* sub_p = sub;
while (*str_start)
{
str_p = str_start;
sub_p = sub;
while (*sub_p && *str_p == *sub_p)
{
str_p++; sub_p++;
}
if (*sub_p == '\0')
{
return str_start;
}
str_start++;
}
return NULL;
}
int main()
{
char* str = "hello 123 abc!";
const char* sub = "123";
printf("%s\n", myStrstr(str, sub));
system("pause");
return 0;
}
模拟实现strcmp
#include<stdio.h>
#include<windows.h>
#include<assert.h>
int myStrcmp(const char* str1, const char* str2)
{
assert(str1);
assert(str2);
int ret = 0;
while (!(ret = *(unsigned char*)str1 - *(unsigned char*)str2) && *str1)
{
str1++; str2++;
}
if (ret > 0)
{
return 1;
}
else if (ret < 0)
{
return -1;
}
else
return 0;
}
int main()
{
const char* str1 = "hello 123 abc!";
const char* str2 = "hello 123 abc!";
printf("ret = %d\n", myStrcmp(str1, str2));
system("pause");
return 0;
}
|