找回密碼
 立即注冊(cè)

QQ登錄

只需一步,快速開(kāi)始

搜索
查看: 3178|回復(fù): 0
收起左側(cè)

strncat函數(shù)實(shí)現(xiàn)及簡(jiǎn)單應(yīng)用

[復(fù)制鏈接]
ID:51090 發(fā)表于 2014-9-24 22:33 | 顯示全部樓層 |閱讀模式

//:Vc++6.0  String  strncat函數(shù)
//功能:按照num數(shù)量連接num個(gè)字符
//參數(shù):dest 目標(biāo)字符串  str 連接字符串  num 連接個(gè)數(shù)
//返回值:目標(biāo)字符串
#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修飾的,否則編譯不通過(guò)
    int len;
while (*(temp1++) != '\0');
len = temp1 - str;
temp1 = str;

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

    if (num <= 0) //當(dāng)num值小于0時(shí),不連接
        *temp = '\0';
    else if (num >= len) //當(dāng)num值大于字符長(zhǎng)度時(shí),全部連接
    {
        while (*(temp1) != '\0')
        {
            *(temp++) = *(temp1++);
        }
        *temp = '\0';
    }
    else
    {
        for (int i = 0; i < num; i++)
        {
            *(temp++) = *(temp1++);
        }
        *temp = '\0';
    }
return dest;
}

//在vc++6.0中的運(yùn)行結(jié)果為:str1 = heiheihello//:~


回復(fù)

使用道具 舉報(bào)

本版積分規(guī)則

手機(jī)版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機(jī)教程網(wǎng)

快速回復(fù) 返回頂部 返回列表