strcpy/strncpy/strcat/strcmp/strlen函数的c语言实现

1、strcpy

头文件:#include <string.h>

函数原型:char *strcpy(char *dest, const char *src)

功能:将字符串src拷贝到dest处

参数:src 为源字符串的起始地址,dest为目标串的起始地址

返回值:目标串dest的起始地址

注意:strcpy只用于字符串复制,不需要指定长度,遇到被复制字符的串结束符"\0"(包括结束符“\0”也会一起复制)才结束,所以容易溢出。

c代码:

char *strCpy(char *dest, const char *src)
{

	if (NULL == dest || NULL == src)
		return NULL;
	
	char *tempDest = dest;
	while ((*dest++ = *src++) != '\0');
	return tempDest;
}

 
2、strncpy 

头文件:#include <string.h>

函数原型:char *strncpy(char *dest, const char *src, size_t n)

功能:将字符串src前n个字符拷贝到dest处

参数:src 为源字符串的起始地址,dest为目标串的起始地址

返回值:目标串dest的起始地址

注意:strncpy 只复制指定的src的前n位,所以dest串没有结束符‘\0’。

c代码:

char *strNcpy(char *dest, const char *src, size_t n)
{
	if (NULL == dest || NULL == src || n < 0)
		return NULL;

	char *tempDest = dest;

	while (n-- > 0)
		*dest++ = *src++;
	
	//*dest = '\0';	  //此处不是函数的实现,为了测试而添加

	return tempDest;
}

 

2015年07月03(修改)

今天去查strnpy函数的时候,上面有这样一句话,If the length of src is less than n, strncpy() pads  the  remainder  of dest with null bytes.大致意思是说如果src字符串的长度小于n,则dest中剩下的部分由‘\0’填充。

上方函数的实现没有体现这一功能,也没有对src字符串的长度作检查,故修改为如下:

改:

char *strNcpy(char *dest, const char *src, size_t n)
{
    if (NULL == dest || NULL == src || n < 0)
	return NULL;
    size_t i;

    for (i = 0; i < n && src[i] != '\0'; i++)
        dest[i] = src[i];
    for ( ; i < n; i++)
        dest[i] = '\0';

     return dest;
}

 

 
 
 

3、strcat

头文件:#include <string.h>

函数原型:char *strcat(char *dest, const char *src)

功能:将字符串src的字符链接在dest的字符串后面,并在dest串末尾添加‘\0’

参数:src 为源字符串的起始地址,dest为目标串的起始地址

返回值:目标串dest的起始地址

c代码:

har *strCat(char *catDest, const char *catSrc)
{
	if (NULL == catDest || NULL == catSrc)
		return NULL;
	char *pDest = catDest;
	while (*pDest != '\0')
		pDest++;
	while ((*pDest++ = *catSrc++) != '\0');

	return catDest;
}

 
4、strcmp 

头文件:#include <string.h>

函数原型:int strcmp(const char *s1, const char *s2)

功能:按照ASCII码顺序比较字符串s1和字符串s2的大小

参数:s1、s2 分别为两字符串的起始地址

返回值:比较结果

s1 > s2, 返回值大于0 

s1 = s2, 返回值等于0

s1 < s2, 返回值小于0

c代码:

方法一:

int strCmp(const char *s1, const char *s2)
{
	if (NULL == s1 || NULL == s2)
		return ERROR;   //ERROR定义的宏 ,为了返回错误

	while (*s1 && *s2 && *s1 == *s2)
	{
		++s1;
		++s2;
	}

	return (*s1 - *s2);
}

 
方法二: 

int strCmpOther(const char *s1, const char *s2)
{
	if (NULL == s1 || NULL ==s2)
		return ;
	while (*s1 || *s2)
	{
		if (*s1 - *s2)
			return (*s1 - *s2);
		else
		{
			++s1;
			++s2;
		}
	}
	return 0;
}

 
5、strlen 

头文件:#include <string.h>

函数原型:size_t strlen(const char *s)

功能:求字符串的长度(不含字符串结束标志‘\0’)

参数:s为字符串

返回值:字符串的长度(不含字符串结束标志‘\0’)

c代码:

size_t strLen(const char *s)
{
	if (NULL == s)
		return -1;
	size_t len = 0;

	while ((*s++) != '\0')
	{
		++len;
	}

	return len;	
}

 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值