c++的c风格字符串函数的实现
要注意使用断言判断传入的字符串非空。
1 #include <cassert> 2 3 //求字符串长度 4 size_t StrLen(const char *str) 5 { 6 assert(str != nullptr); 7 size_t len = 0; 8 while (*str++ != '\0') 9 { 10 ++len; 11 } 12 return len; 13 } 14 15 16 //复制字符串 17 char* StrCpy(char *dest, const char *src) 18 { 19 assert(dest != nullptr && src != nullptr); 20 char *temp = dest; 21 while ((*dest++ = *src++) != '\0'); 22 return temp; 23 } 24 25 //复制指定长度字符串 26 char* StrNCpy(char *dest, const char *src, size_t n) 27 { 28 assert(dest != nullptr && src != nullptr); 29 char *temp = dest; 30 size_t i = 0; 31 while (i++ < n && (*dest++ = *src++) != '\0'); 32 if (*dest != '\0') 33 { 34 *dest = '\0'; 35 } 36 return temp; 37 } 38 39 //比较字符串 40 int StrCmp(const char *lhs, const char *rhs) 41 { 42 assert(lhs != nullptr && rhs != nullptr); 43 int ret = 0; 44 while (!(ret = *(const unsigned char *)lhs - *(const unsigned char *)rhs) && *rhs) 45 { 46 ++lhs; 47 ++rhs; 48 } 49 if (ret > 0) 50 { 51 return 1; 52 } 53 else if (ret < 0) 54 { 55 return -1; 56 } 57 else 58 { 59 return 0; 60 } 61 } 62 63 //拼接字符串 64 char* StrCat(char *dest, const char *src) 65 { 66 assert(dest != nullptr && src != nullptr); 67 char *temp = dest; 68 while (*dest != '\0') 69 { 70 ++dest; 71 } 72 while ((*dest++ = *src++) != '\0'); 73 return temp; 74 } 75 76 //附:实现memcpy()函数 77 void* MemCpy(void *dest, const void *src, size_t n) 78 { 79 assert(dest != nullptr && src != nullptr); 80 //不可直接对void类型的指针进行操作 81 char *temp_dest = (char*)dest; 82 const char *temp_src = (char*)src; 83 while (n--) 84 { 85 *temp_dest++ = *temp_src++; 86 } 87 return dest; 88 } 89 90 //附2:实现memset()函数 91 void* MemSet(void *buffer, int c, size_t n) 92 { 93 assert(buffer != nullptr); 94 char *temp = (char*)buffer; 95 while (n--) 96 { 97 *temp++ = (char)c; 98 } 99 return buffer; 100 }