当前位置: 代码迷 >> 综合 >> 字符串常用操作(strlen,strcpy,strcat,strcmp,strncpy,strncat)
  详细解决方案

字符串常用操作(strlen,strcpy,strcat,strcmp,strncpy,strncat)

热度:26   发布时间:2023-12-08 19:41:07.0


#include <assert.h>
#include <stddef.h>
// strlen的实现
int mystrlen(const char *s)
{int len = 0;while (*s ++!= '\0'){len ++;}return len;
}
//strcpy的实现
char *mystrcpy(char *dest, const char *src)
{char *tmp = dest;assert((dest!= NULL) && (src != NULL));while (*dest ++ = *src ++);return tmp;
}
//strncpy的实现
char *mystrncpy(char *dest,const char *src, size_t n)
{char *temp = dest;assert((dest!= NULL) && (src != NULL));while (n-- && (*dest++ = *src++));if(n){while (--n)*dest = '\0';}*dest = '/0';return temp;
}
//strcat的实现
char *mystrcat(char *dest, const char *src)
{assert((dest!= NULL) && (src != NULL));char *tmp = dest;while (*tmp)tmp++;while (*tmp++ = *src++);return dest;
}
//strncat的实现
char *mystrncat(char *dest,const char *src, size_t n)
{assert((dest!= NULL) && (src != NULL));char *tmp = dest;while (*dest)dest++;while(n-- > 0 && (*dest ++ = *src ++));return tmp;
}
//strcmp的实现
int mystrcmp(char *str1, char *str2)
{while (*str1 ++ == *str2 ++)if (*str1 == '\0')return 0;return *(--str1) - *(--str2);
}

  相关解决方案