最近是校招很热的季节,实验室里讨论最多的也就是算法,面试和笔试的必备知识储备。昨天想起 C 语言中 string.h 中的函数在操作字符串时很方便,所以,就想起写写那些函数。
当然,这些函数实现的只是简单的功能,并没有加入太多的排错功能,欢迎大家及时指正代码中出现的问题,谢谢!
my_string.h
#include <stdio.h>#include <stdlib.h>int my_strcmp(char *string1, char *string2);int my_strlen(char *string);char *my_strcat(char *res, const char *string);char *my_strcpy(const char *sou, char *dest);const char *my_strchr(char const *str,int ch);const char *my_strstr(char const *s1,char const *s2);
my_string.c
#include <stdio.h>#include <stdlib.h>#include "my_string.h"int my_strcmp(char *string1, char *string2){char *index1 = string1;char *index2 = string2;while (*index1 == *index2 && *index1 != ' ' && *index2 != ' '){index1++;index2++;}if (*index1 - *index2 > 0){return 1;}else if (*index1 - *index2 < 0){return -1;}else{return 0;}}int my_strlen(char *string){char *temp = string;int count = 0;if (string == NULL || *string == ' '){return 0;}while (*temp != ' '){temp++;count++;}return count;}char *my_strcat(char *res, const char *string){char *ret = res;if (string == NULL || *string == ' '){return res;}while (*res != ' '){res++;}while (*string != ' '){*res++ = *string++;}*res = ' ';return ret;}char *my_strcpy(const char *sou, char *dest){char *addr = dest;if (dest == NULL || sou == NULL){return NULL;}while (*sou != ' '){*dest++ = *sou++;}*dest = ' ';return addr;}const char *my_strchr(char const *str,int ch){if (str == NULL || *str == ' '){return NULL;}while (*str != ch && *str != ' ')str++;if (*str == ch)return str;elsereturn NULL;}/*************************************************/const char *my_strstr(char const *s1,char const *s2){int n;if (*s2 == ' ' || s2 == NULL){return s1;}while (*s1 != ' '){for (n = 0; *(s1 + n) == *(s2 + n); n++){if (*(s2 + n + 1) == ' ')return s1;}s1++;}return NULL;}/*************************************************/