strstr、strcmp、strlen、strcpy
const char* strstr(const char *str, const char* substr) { int i, j, temp; for (i = 0; str[i] != '\0'; i++) { j = 0; temp = i; //记录当前主字符串位置 while (str[i++]==substr[j++]) { if (substr[j] == '\0') { return &str[temp]; } else if (str[i]=='\0') { return NULL; } } } return NULL; }
int strcmp(const char* str1, const char* str2) { while (*str1==*str2) { if (*str1 == '\0') { return 0; } ++str1; ++str2; } return *str1 - *str2; }
unsigned int strlen(const char* str) { const char* res = str; while (*res++); //res跳出循环后,仍执行++ return (res - str - 1); }
char* strcpy(char *dst,const char* src) { assert(0==dst||0==src); char* tmp = dst; while (*src!='0') { *dst++ = *src++; } *dst = '\0'; return tmp; }
strcpy为较安全的做法,且构造成易于实现链式表达式的形式。