strcpy
#include <string.h>
#include <assert.h>
char * strcpy( char *strDest, const char *strSrc ) //将源字符串加const,表明其为输入参数
{
assert( (strDest != NULL) &&(strSrc != NULL) ); //对源地址和目的地址加非0断言,检查指针的有效性
char *str = strDest;
while( (*strDest++ = * strSrc++) != ‘\0‘ );//循环体结束后,strDest字符串的末尾正确地加上‘\0‘
return str; //为了实现链式操作,将目标地址返回
}
strncpy
#include <string.h>
char * strncpy (char * dest,const char * source,int count)
{
char *start = dest;
while (count && (*dest++ =*source++)) /* copy string */
count--;
if (count) /* pad out with zeroes */
while (--count)
*dest++ = ‘\0‘;
return(start);
}
strcmp
#include <string.h>
int strcmp(const char *str1,const char *str2)
{
/*不可用while(*str1++==*str2++)来比较,当不相等时仍会执行一次++,
return返回的比较值实际上是下一个字符。应将++放到循环体中进行。*/
while(*str1 == *str2)
{
if(*str1 == ‘\0‘)
return0;
str1++;
str2++;
}
return *str1 - *str2;
}
strncmp
//不区分大小写
int strncmp(const char * s1, const char * s2, size_t len)
{
while(len--) {
if(*s1 == 0 || *s1 != *s2)
return *s1 - *s2;
s1++;
s2++;
}
return 0;
}
//区分大小写
#include <ctype.h>
int strnicmp(const char * s1, const char * s2, size_t len)
{
register signed char r;
while(len--) {
if((r = toupper(*s1) - toupper(*s2)) || *s1 == 0)
return r;
s1++;
s2++;
}
return 0;
}
strlen
size_t strlen_a(const char *str) {
size_t length = 0;
while (*str++)
++length;
return length;
}
size_t strlen_b(const char *str) {
const char *cp = str;
while (*cp++);
return (cp - str - 1);
}