string函数的一些实现
1 /************************************************************************* 2 > File Name: test.cpp 3 ************************************************************************/ 4 #include"stdlib.h" 5 #include"stdio.h" 6 #include"string.h" 7 8 char *mystrcat(char *dest,const char *src) 9 { 10 char* temp = dest; 11 while(*dest != '\0') 12 { 13 dest++; 14 } 15 16 while((*dest++ = *src++) != '\0'); 17 18 return temp; 19 } 20 char *mystrncat(char *dest,const char *src,size_t n) 21 { 22 23 char* temp = dest; 24 while(*dest != '\0') 25 { 26 dest++; 27 } 28 29 while(n-->0 && (*dest++ = *src++) != '\0'); 30 31 return temp; 32 } 33 34 35 36 void* mymemset(void *s, int c, size_t n ) 37 { 38 unsigned char uc = c; 39 unsigned char *su = (unsigned char*)s; 40 while(n-->0) 41 { 42 *su = uc; 43 su++; 44 } 45 } 46 47 int mystrlen(const char* str) 48 { 49 return *str?(mystrlen(++str)+1):0; 50 /* 51 const char* eos = str; 52 while(*eos++); 53 return (eos-str-1); 54 */ 55 } 56 57 void* mymemcpy(void*dst, const void* src,size_t size) 58 { 59 60 if(src==NULL || dst==NULL) return NULL; 61 void* ret = dst; 62 while(size--) 63 { 64 *(char*)dst = *(char*)src; 65 dst = (char*)dst + 1; 66 src = (char*)src + 1; 67 } 68 return ret; 69 } 70 71 void* mymemmove(void*dst, const void* src,size_t size) 72 { 73 if(src==NULL || dst==NULL) return NULL; 74 char* psrc; 75 char* pdst; 76 //存在覆盖,自后向前进行拷贝 77 if((src<dst) && (char*)src+size > (char*)dst) 78 { 79 psrc = (char*)src + size-1; 80 pdst = (char*)dst + size-1; 81 while(size--) 82 *pdst-- = *psrc--; 83 } 84 else 85 { 86 psrc = (char*)src; 87 pdst = (char*)dst; 88 while(size--) 89 { 90 *pdst++ = *psrc++; 91 } 92 } 93 } 94 95 int mymemcmp(const void * ptr1, const void * ptr2, size_t num) 96 { 97 if(ptr1==NULL || ptr2==NULL || num<0) return 0; 98 99 char* pch1 = (char*)ptr1; 100 char* pch2 = (char*)ptr2; 101 102 while(num-- && *pch1++ == *pch2++); 103 return (pch1-pch2)<<8; 104 } 105 106 int mystrcmp ( const char * str1, const char * str2 ) 107 { 108 if(str1==NULL || str2 ==NULL) return 0; 109 110 while(*str1 == *str2) 111 { 112 str1++; 113 str2++; 114 } 115 116 return (*str1-*str2); 117 } 118 119 int mystrncmp( const char * str1, const char * str2, size_t num ) 120 { 121 122 if(str1==NULL || str2 ==NULL) return 0; 123 124 while(num-- && *str1 == *str2) 125 { 126 str1++; 127 str2++; 128 } 129 130 return (*str1-*str2); 131 } 132 133 int main() 134 { 135 char ch1[] = "hello"; 136 char ch2[] = "herld"; 137 // printf("strcat : %s\n", mystrncat(ch1,ch2,2)); 138 139 printf("%d\n",mystrcmp(ch2,ch1)); 140 141 printf("%d\n",mystrncmp(ch2,ch1,4)); 142 143 144 return 0; 145 }