標(biāo)題: strncat函數(shù)實(shí)現(xiàn)及簡(jiǎn)單應(yīng)用 [打印本頁]

作者: xiaojuan    時(shí)間: 2014-9-24 22:33
標(biāo)題: strncat函數(shù)實(shí)現(xiàn)及簡(jiǎn)單應(yīng)用

//: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修飾的,否則編譯不通過
    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//:~







歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1