找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 3206|回复: 0
收起左侧

strncat函数实现及简单应用

[复制链接]
ID:51090 发表于 2014-9-24 22:33 | 显示全部楼层 |阅读模式

//: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//:~


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表