#include<stdio.h> #include<assert.h> //指针streln //int my_strlen(const char *src) //{ // int count = 0; // while (*src++) // count++; // return count; //} //数组strlen //int my_strlen(const char src[]) //{ // int count = 0; // while (src[count]) // count++; // return count; //} //递归strlen int my_strlen(const char *src) { if (‘\0‘ == *src) return 0; else return my_strlen(++src) + 1; } char *my_strstr(const char *dest, const char *src) { assert(dest); assert(src); char *pdest = dest,*s1=NULL,*s2=NULL; if (!*src) return dest; while (*pdest) { s1 = pdest; s2 = src; while (*s1 && *s2 && !(*s1 - *s2)) s1++, s2++; if (!*s2) return pdest; pdest++; } return NULL; } char *my_strcpy(char *dest,const char *src) { assert(dest); assert(src); const char *pdest = dest; while (*src) { if (‘\0‘ == *dest) return pdest; *dest++ = *src++; } return pdest; } char *my_strcat(char *dest, char *src) { assert(dest); assert(src); char *psrc = src; while (*src) src++; while (*dest) *src++ = *dest++; *src = ‘\0‘; return psrc; } int my_strcmp(const char *dest, const char *src) { assert(dest); assert(src); while (*dest && *src && !(*src - *dest)) dest++,src++; return (*src - *dest); } void *my_memcpy(void *dest, const void *src,size_t len) { assert(dest); assert(src); char *pdest = (char *)dest; char *psrc = (char *)src; while (len--) { *pdest = *psrc; pdest++, psrc++; } return (char *)dest; } void *my_memmove(void *dest, void *src, size_t count) { assert(dest); assert(src); char *pdest = (char *)dest; char *psrc = (char *)src; if (pdest <= psrc || pdest >= (psrc+count))//防止dest的头部和src的尾部接触的情况进入循环(判断需要正向拷贝) { while (count--) { *pdest = *psrc; pdest++, psrc++; } } else//只有dest的头部和src的尾部接触才需要倒序拷贝 { pdest = (char *)dest + count; psrc = (char *)src + count; while (count--) { *pdest = *psrc; *pdest--, *psrc--; } } return (char *)dest; } int main() { char arr[20] = "123456789"; char arr2[] = "456"; char arr3[20] = "000000000"; char arr4[] = "87654321"; char arr5[] = "123456889"; char arr6[20] = { 1, 2, 3, 4, 5 }; char arr7[20] = { 0 }; printf("len=%d,loc=%p\n", my_strlen(arr),my_strstr(arr,arr2)); printf("%d\n", my_strcmp(arr5, arr)); printf(my_strcpy(arr3, arr)); printf("\n"); printf(my_strcat(arr4, arr)); printf("\n"); my_memcpy(arr7, arr6,20); my_memmove(arr7, arr6, 12); system("pause"); return 0; }
时间: 2024-10-26 22:51:13