c语言实现My_string
发表于:2024-11-26 作者:热门IT资讯网编辑
编辑最后更新 2024年11月26日,实现strcpy strcat strstr strchr strcmp memcpy memovechar my_strcpy(char *dest, const char *src)//实现str
实现strcpy strcat strstr strchr strcmp memcpy memove
char my_strcpy(char *dest, const char *src)//实现strcpy{ assert(dest); assert(src); while (*src) { *dest = *src; dest++; src++; } *dest = '\0';}int main(){ char dest[20] ="1234567890"; char src []= "abcdef"; my_strcpy(dest, src); printf("%s\n", dest); system("pause"); return 0;}
#include#includechar my_strcat(char *dest, const char *src)//实现strcat{ assert(dest); assert(src); while (*dest != '\0') { dest++; } while (*src != '\0') { *dest = *src; dest++; src++; }}int main(){ char dest[20] = "1234567890"; char src []= "abcdef"; my_strcat(dest, src); printf("%s", dest); system("pause"); return 0;}
#includeconst char *Mystrchr(const char *src, char ch)//实现strchr{ while (*src != '\0') { if (*src == ch) { return src; } src++; } return NULL;}int main(){ char str[10] = "abcdefg"; char a = 'b'; printf("%s", Mystrchr(str,a)); system("pause"); return 0;}
#include#includeconst char *My_strstr(const char *str1, const char *str2)实现strstr{ const char *s1 = NULL; const char *s2 = NULL; const char *start = str1; while (*start != '\0') { s1 = start;//s1回退到上一次的下一个位置 s2 = str2;//s2回退到str2的起始位置 while (*s1 != '\0' && *s2 != '\0'&&*s1 == *s2) { s1++; s2++; } if (*s1 == '\0') { return NULL; } if (*s2 == '\0') { return start; } start++; } return NULL;}int main(){ char dest[20] = "123aabcdef90"; char src []= "abcdef"; printf("%s\n", My_strstr(dest, src)); system("pause"); return 0;}
#include#includeint* my_strcmp(char *dest, const char *src)实现strcmp{ assert(dest); assert(src); while (*dest != '\0'&&*src!='\0') { if (*dest == *src) { dest++; src++; } else if (*dest > *src) { return 1; } else { return -1; } } return 0;}int main(){ char dest[] = "abcdef"; char src []= "adcdef"; int ret = my_strcmp(dest, src); printf("%d",ret); system("pause"); return 0;}
#include#includevoid *Mymemcpy(void *dest, const void *src, int count)//实现mencpy{ while (count != 0) { *((char*)dest) = *((char*)src); ((char*)dest)++; ((char*)src)++; count--; }}int main(){ int arr[10] = {1,2,3,4,5,6,7,8,9}; int arr2[10] = {0}; int i = 0; Mymemcpy(arr2,arr,16); for (; i < 10; i++) { printf("%d",arr2[i]); } system("pause"); return 0;}#include#includevoid *Mymemcpy(void *dest, const void *src, int count)//实现memcpy//count是字节数{ while (count != 0) { *((char*)dest) = *((char*)src); ((char*)dest)++; ((char*)src)++; count--; }}int main(){ int arr[10] = {1,2,3,4,5,6,7,8,9}; int arr2[10] = {0}; int i = 0; Mymemcpy(arr2,arr,16); for (; i < 10; i++) { printf("%d",arr2[i]); } system("pause"); return 0;}