# 不使用库函数、自己编写的（strlen、strcpy、strcmp、strcat、memcmp、memcpy、memmove）

  1 //求字符串长度的函数
2 int my_strlen(const char* pStr)
3 {
4 assert(pStr != NULL);
5 int length = 0;
6 while (*pStr++ != '\0')
7 {
8 length++;
9 }
10 return length;
11 }
12 //字符串拷贝函数
13 char* my_strcpy(char* strDest, const char* strSrc)
14 {
15 assert(strDest != NULL && strSrc != NULL);
16 char* pDest = strDest; //保护参数
17 const char* pSrc = strSrc;
18 while (*pSrc != '\0')
19 {
20 *pDest++ = *pSrc++;
21 }
22 //*pDest = '\0';
23 return strDest;
24 }
25 //字符串比较函数
26 int my_strcmp(const char* strDest, const char* strSrc)
27 {
28 assert(strDest != NULL && strSrc != NULL);
29 if (*strDest == '\0'&&*strSrc != '\0')
30 {
31 return 0;
32 }
33 const char* pDest = strDest;
34 const char* pSrc = strSrc;
35 int result = 0; //用于记录比较结果
36 while (*pDest != '\0' || *pSrc != '\0')
37 {
38 if ((result = *pDest - *pSrc) != 0)
39 {
40 break;
41 }
42 pDest++;
43 pSrc++;
44 }
45 if (result > 0)
46 {
47 result = 1;
48 }
49 else if (result<0)
50 {
51 result = -1;
52 }
53 return result;
54 }
55 //字符串连接函数
56 char* my_strcat(char* strDest, char* strSrc)
57 {
58 assert(strDest != NULL && strSrc != NULL);
59 char* pDest = strDest;
60 char* pSrc = strSrc;
61 while(*pDest != '\0')
62 {
63 pDest++;
64 }
65 while (*pSrc != '\0')
66 {
67 *pDest++ = *pSrc++;
68 }
69 *pDest = '\0';
70 return strDest;
71 }
72
73 //内存比较函数
74 int my_memcmp(void* src1, void* src2, int len)
75 {
76 assert(src1 != NULL && src2 != NULL);
77 const char* pSrc1 = (char*)src1;
78 const char* pSrc2 = (char*)src2;
79 while (len-- > 0)
80 {
81 if (*pSrc1++ != *pSrc2++)
82 {
83 return *pSrc1 < *pSrc2 ? -1 : 1;
84 }
85 }
86 return 0;
87 }
88
89 //内存拷贝函数
90 void* my_memcpy(void* dest, const void* src, size_t count)
91 {
92 assert(dest != NULL && src != NULL);
93 char* pDest = (char*)dest;
94 const char* pSrc = (const char*)src;
95 while (count-- > 0)
96 {
97 *pDest++ = *pSrc++;
98 }
99 return dest;
100 }
101
102 //内存移动函数
103 void* my_memmove(void* dest, void* src, size_t count)
104 {
105 assert(dest != NULL && src != NULL);
106 char* pDest = (char*)dest;
107 const char* pSrc = (char*)src;
108 　　　　 if (pSrc >= pDest || pDest >= (pSrc + count))
109 {
110
111
112 　　　　while (count-- > 0)
113         {
114              *pDest++ = *pSrc;
115        }
116 }
117 else
118 　{
119       while (count-- > 0)
120
121           {
122
123               *(pDest + count) = *(pSrc + count);
124          }
125 }
126 *pDest = '\0';
127 return dest;
128 }

posted @ 2016-04-19 10:46  A_carat_tear  阅读(540)  评论(0编辑  收藏