💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# C `strncat()`函数 > 原文: [https://beginnersbook.com/2017/11/c-strncat-function/](https://beginnersbook.com/2017/11/c-strncat-function/) 在上一个教程中,我们讨论了 [`strcat()`函数](https://beginnersbook.com/2017/11/c-strcat-function-with-example/),它用于将一个字符串连接到另一个字符串。在本指南中,我们将看到类似的**`strncat()`函数**,它与 `strcat()`相同,只是 `strncat()`只将指定数量的字符附加到目标字符串。 ## C `strncat()`函数声明 ```c char *strncat(char *str1, const char *str2, size_t n) ``` `str1` - 目标字符串。 `str2` - 附加在目标字符串`str1`末尾的源字符串。 `n` - 需要追加的源字符串`str2`的字符数。例如,如果这是 5,则只有源字符串`str2`的前 5 个字符将附加在目标字符串`str1`的末尾。 **返回值:**该函数返回指向目标字符串`str1`的指针。 ## 示例:C 中的`strncat()`函数 ```c #include <stdio.h> #include <string.h> int main () { char str1[50], str2[50]; //destination string strcpy(str1, "This is my initial string"); //source string strcpy(str2, ", add this"); //displaying destination string printf("String after concatenation: %s\n", strncat(str1, str2, 5)); // this should be same as return value of strncat() printf("Destination String str1: %s", str1); return 0; } ``` 输出: ```c String after concatenation: This is my initial string, add Destination String str1: This is my initial string, add ``` 正如您所看到的,在字符串`str1`的末尾只连接了字符串`str2`的 5 个字符,因为我们在 `strncat()`函数中将`count`指定为 5。 另一个**需要注意的重点是**这个函数返回指向目标字符串的指针,这就是为什么当我们显示 `strncat()`的返回值时,它与目标字符串`str1`相同。