strlen strcat strcpy strcmp 自己实现
程序员文章站
2022-03-14 10:09:05
strlen strcat strcpy strcmp 自己实现 strlen strcat strcpy strcmp c include include include include int my_strcmp(const char s1, const char s2){ assert(NUL ......
strlen strcat strcpy strcmp 自己实现
strlen
include <stdio.h> #include <string.h> #include <assert.h> size_t my_strlen(const char* str){ assert(str != NULL); const char *tmp = str; size_t count = 0; while(*tmp++ != '\0'){ count++; } return count; } size_t my_strlen1(const char* str){ assert(str != NULL); if(*str == 0){ return 0; }else{ return my_strlen1(str+1) + 1; } } int main(){ char as[] = "hello C"; printf("%ld\n",strlen(as)); printf("%ld\n",my_strlen(as)); printf("%ld\n",my_strlen1(as)); }
strcat
#include <stdio.h> #include <string.h> #include <assert.h> #include <malloc.h> char* my_strcat(char* strd, const char* strs){ assert(strd != NULL && strs != NULL); char *tmp = strd; while(*tmp++ != 0){} tmp--; while(*strs != 0){ *(tmp++) = *strs++; } *tmp = '\0'; return strd; } int main(){ char s1[20] = "hello"; char s2[] = " C"; printf("strcat before s1 = %s\n", s1); char *str = my_strcat(s1,s2); printf("strcat after s1 = %s\n", s1); printf("strcat after str = %s\n", str); }
strcpy
#include <stdio.h> #include <string.h> #include <assert.h> #include <malloc.h> char* my_strcpy(char* strd, const char* strs){ assert(NULL != strd && NULL != strs); char* tmp = strd; while(*strs != '\0'){ *tmp++ = *strs++; } *tmp = '\0'; return strd; } int main(){ char s1[20] = "hello"; char s2[] = " wod"; printf("strcpy before s1 = [%s]\n", s1); char *str = my_strcpy(s1,s2); printf("strcpy after s1 = [%s]\n", s1); printf("strcat after str = [%s]\n", str); }
strcmp
#include <stdio.h> #include <string.h> #include <assert.h> #include <malloc.h> int my_strcmp(const char *s1, const char *s2){ assert(NULL != s1 && NULL != s2); int res = 0; while(*s1 != '\0' || *s2 != '\0'){ if(*s1 > *s2){ res = 1; break; }else if(*s1 < *s2){ res = -1; break; }else{ s1++; s2++; } } return res; } int main(){ char *s1 = "a1123"; char *s2 = "a1123"; int res = my_strcmp(s1, s2); if(res == 0){ printf("s1 == s2\n"); }else if(res > 0){ printf("s1 > s2\n"); }else{ printf("s1 < s2\n"); } }
推荐阅读
-
strlen、strcpy、strcat函数的自主实现
-
PHP 语法字符串函数 strcmp、strlen 使用及实现
-
C/C++实现strcpy和strcat两个功能
-
strlen strcat strcpy strcmp 自己实现
-
用c语言.模拟实现strcpy,strcat,strcat,memcpy,memmove
-
C语言模拟实现strcat、strcmp和strcpy,详解代码及过程
-
自制函数实现strlen、strcpy、strcmp、strcat函数
-
POJ3087 Shuffle'm Up (strcmp;strcpy;strcat)
-
PHP 语法字符串函数 strcmp、strlen 使用及实现
-
strlen strcat strcpy strcmp 自己实现