标题: strncat函数实现及简单应用 [打印本页]

作者: xiaojuan    时间: 2014-9-24 22:33
标题: strncat函数实现及简单应用

//:Vc++6.0  String  strncat函数
//功能:按照num数量连接num个字符
//参数:dest 目标字符串  str 连接字符串  num 连接个数
//返回值:目标字符串
#include<stdio.h>

char *strncat(char *dest, const char *str, int num);

int main()
{
char str1[20] = "hello ";
char str2[20] = "world haha";
char str3[20] = "heihei";
strncat(str3, strncat(str1, str2, 6), 5);
printf("str1 = %s\n", str3);
return 0;
}

char *strncat(char *dest, const char *str, int num)
{
if (dest == NULL || str == NULL)
{
perror("dest or str");
return NULL;
}
char *temp = dest;
const char *temp1 = str; //前面必须是const修饰的,否则编译不通过
    int len;
while (*(temp1++) != '\0');
len = temp1 - str;
temp1 = str;

    while (*(temp++) != '\0');
    temp--;

    if (num <= 0) //当num值小于0时,不连接
        *temp = '\0';
    else if (num >= len) //当num值大于字符长度时,全部连接
    {
        while (*(temp1) != '\0')
        {
            *(temp++) = *(temp1++);
        }
        *temp = '\0';
    }
    else
    {
        for (int i = 0; i < num; i++)
        {
            *(temp++) = *(temp1++);
        }
        *temp = '\0';
    }
return dest;
}

//在vc++6.0中的运行结果为:str1 = heiheihello//:~







欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1