strcpy()、memcpy()、memmove()、memset() 、strcmp()、strlen()、strcat()的实现
View Code
1 strcpy(), 字符串拷贝.
2 char *strcpy(char *strDest, const char *strSrc)
3 {
4 assert((strDest!=NULL) && (strSrc !=NULL));
5 char *address = strDest;
6 while( (*strDest++ = * strSrc++) != '\0')
7 NULL ;
8 return address ;
9 }
10
11 memcpy, 拷贝不重叠的内存块
12 void *memcpy(void* pvTo, void* pvFrom, size_t size) //byte是java里的变量类型
13 {
14 assert(pvTo != NULL && pvFrom != NULL);
15 void* pbTo = (byte*)pvTo;
16 void* pbFrom = (byte*)pvFrom;
17 /* 内存块重叠吗?如果重叠,就使用memmove */
18 assert(pbTo>=pbFrom+size || pbFrom>=pbTo+size);
19 while(size-->0)
20 *pbTo++ == *pbFrom++;
21 return pvTo;
22 }
23
24 void *MemCopy(void *dest,const void *src,size_t count)
25 {
26 char *pDest=static_cast<char *>(dest);
27 const char *pSrc=static_cast<const char *>(src);
28 if( pDest>pSrc && pDest<pSrc+count )
29 {
30 for(size_t i=count-1; i<=0; ++i)
31 {
32 pDest[i]=pSrc[i];
33 }
34 }
35 else
36 {
37 for(size_t i=0; i<count; ++i)
38 {
39 pDest[i]=pSrc[i];
40 }
41 }
42 return pDest;
43 }
44
45 void *Memmove(void *Dst, const void*Src,size_t count)
46 {
47 assert(Dst && Src);
48 void* pDst = Dst;
49 if (Dst<Src && (char*)Dst > (char*)Src + count)
50 {
51 while(count--)
52 {
53 *(char*)Dst = *(char*)Src;
54 Dst = (char*)Dst + 1;
55 Src = (char*)Src + 1;
56 }
57 }
58 else
59 {
60 Dst = (char*)Dst + count - 1;
61 Src = (char*)Src + count - 1;
62 while(count--)
63 {
64 *(char*)Dst = *(char*)Src;
65 Dst = (char*)Dst -1 ;
66 Src = (char*)Src -1 ;
67 }
68 }
69 return pDst;
70 }
71
72
73 void* memmove(void *dest, const void *src,size_t n)
74 {
75 if (n == 0) return 0;
76 if (dest == NULL) return 0;
77 if (src == NULL) return 0;
78 char *psrc = (char*)src;
79 char *pdest = (char*)dest;
80 if((dest <= psrc) || (pdest >= psrc + n)) /*检查是否有重叠问题 */
81 {
82 for(int i=0; i < n; i++) /*正向拷贝*/
83 {
84 *pdest = *psrc;
85 psrc++;
86 pdest++;
87 }
88 }
89 else /*反向拷贝*/
90 {
91 psrc += n;
92 pdest += n;
93 for(int i=0;i<n;i++)
94 {
95 psrc--;
96 pdest--;
97 *pdest = *psrc;
98 }
99 }
100 return dest;
101 }
102
103 memset:把buffer所指内存区域的前count个字节设置成字符c
104
105 void * Memset(void* buffer, int c, int count)
106 {
107 char* pvTo=(char*)buffer;
108 assert(buffer != NULL);
109 while(count-->0)
110 *pvTo++=(char)c;
111 return buffer;
112 }
113
View Code
View Code
1 Char* strcat ( char * dst , const char * src )
2
3 {
4
5 char * cp = dst;
6
7 while( *cp )
8
9 cp++; /* find end of dst */
10
11 while( *cp++ = *src++ ) ; /* Copy src to end of dst */
12
13 return( dst ); /* return dst */
14
15 }
View Code
1 int strlen1(char s[])
2 {
3 int n;
4 n = 0;
5 while (s[n++] != '\0')
6 ;
7 return n;
8 }
View Code
1 int strcmp(const char *dest, const char *source)
2 {
3 assert((NULL != dest) && (NULL != source));
4 while (*dest && *source && (*dest == *source))
5 {
6 dest ++;
7 source ++;
8 }
9 return *dest - *source;
10 /*如果dest > source,则返回值大于0,如果dest = source,则返回值等于0,如果dest < source ,则返回值小于0。*/
11 }