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