题一:
模拟实现strncpy
#include <stdio.h> void my_strncpy(char* arr2, char* arr1, size_t num) { int i = 0; for (i = 0; i < num; i++) { *(arr2 + i) = *(arr1 + i); } } int main() { char arr1[] = "hello liangzai"; char arr2[10] = { 0 }; //strncpy(arr2,arr1,sizeof(arr2)); my_strncpy(arr2, arr1, sizeof(arr2)); return 0; }
优解一:
char * mystrncpy(char * dst, const char * src, size_t n) { int i; for (i = 0; src[i] && i < n; i++) { dst[i] = src[i]; } if (i < n) { dst[i] = 0; } return dst; }
题二:
模拟实现strncat
#include <stdio.h> #include <string.h> char* my_strncat(char* arr1, const char* arr2, size_t num) { int sz = strlen(arr1); int i = 0; for (i = 0; i < num; i++) { *(arr1 + sz + i) = *(arr2 + i); } return arr1; } int main() { char arr2[] = "shawanyi "; char arr1[20] = "hello "; //strncat(arr1,arr2,10); my_strncat(arr1, arr2, 10); return 0; }
优解一:
char * mystrncat(char * dst, const char * src, size_t n) { char * tmp = dst; while (*dst) { dst++;//记录到dst最后一个位置 } int i; for (i = 0; src[i] && i < n; i++) { dst[i] = src[i]; } dst[i] = 0; return tmp; }
题三:
模拟实现atoi
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <ctype.h> int my_atoi(const char* arr1) { assert(arr1); int sum = 0; if (*(arr1) == '\0') { return 0; } while(isspace(*arr1)) { arr1++; } int flat = 1; if (*arr1 == '+') { arr1++; } else if (*arr1 == '-') { flat = -1; arr1++; } int ret = 0; while (isdigit(*arr1)) { ret = ret * 10 + (*arr1 - '0'); if (ret > INT_MAX) { return INT_MAX * flat; } else if (ret < INT_MIN) { return INT_MIN * flat; } arr1++; } if (isdigit(*arr1) == 0) { return ret * flat; } return ret*flat; } int main() { char arr1[] = "-123666a44"; //int n = atoi(arr1); int sz = 0; sz = my_atoi(arr1); return 0; }
优解一
#include <stdio.h> #include <stdlib.h> #include <ctype.h> //VALID 表示结果合法 //INVALID 表示结果非法 enum State { VALID,//0 INVALID//1 }; //默认结果可能非法,当正确转换后再改为合法 enum State state = INVALID; int my_atoi(char *str) { int flag = 1; long long ret = 0; assert(str); state = INVALID; //跳过空白字符 while(isspace(*str)) { str++; } if(*str == '\0') { return 0; } //跳过正负号 if(*str == '+') { str++; } else if(*str == '-') { flag = -1; str++; } //开始转换数字字符直到非数字字符 while(isdigit(*str)) { ret = ret * 10 + flag * (*str-'0'); if((ret > INT_MAX) || (ret < INT_MIN)) { return 0; } str++; } //正常停止 if(*str == '\0') { state = VALID; return (int)ret; } else { //遇到非数字字符 return (int)ret; }