实现memcpy
//从最后一个字符开始往前拷贝,可以解决内存重叠的部分问题
void* Mymemcpy(void* dest, const void* src, size_t count) {
assert(dest != NULL);
assert(src != NULL);
char* p = (char*)dest+(count-1);
const charp1 = (char)src+(count-1);
while (count–) {
p = p1;
–p;
–p1;
}
return dest;
}
int main() {
char buf1[] = “welcome”;
char buf2[64] = { 0 };
Mymemcpy(buf2, buf1, 4);
printf("%s\n", buf2);
return 0;
}
实现strcmp
int strcmp(const char arr1, const char arr2) {
while ((*arr1!=’\0’)&&(*arr2!=’\0’)) {
if (*arr1 > *arr2) {
return 1;
}
else if (*arr1 < arr2) {
return -1;
}
else {
++arr1;
++arr2;
}
}
if ((arr1 == ‘\0’)&&(arr2!=’\0’)) {
return -1;
}
else if ((arr2 == ‘\0’) && (arr1 != ‘\0’)) {
return 1;
}
else {
return 0;
}
}
int main() {
char arr1[] = “hello:”;
char arr2[] = “world!”;
int ret = strcmp(arr1, arr2);
printf("%d\n", ret);
return 0;
}
实现strstr
const char Mystrstr(const char des,const char str) {
assert(des != NULL);
assert(str != NULL);
const char red = des;
const char blk = str;
while (red) {
const char tmp = red;
while (*blk == *tmp) {
blk++;
tmp++;
}
if (blk == ‘\0’) {
return red;
}
blk = str;
red++;
}
return NULL;
}
int main() {
char buf[] = “hello”;
char str[] = “he”;
const charret = Mystrstr(buf, str);
printf("%s\n", ret);
return 0;
}
strcmp strstr memcpy的模拟实现
最新推荐文章于 2023-06-04 14:10:15 发布