在上一个教程中,我们讨论了 strcat()函数,它用于将一个字符串连接到另一个字符串。在本指南中,我们将看到类似的strncat()函数,它与 strcat()相同,只是 strncat()只将指定数量的字符附加到目标字符串。
C strncat()函数声明
char *strncat(char *str1, const char *str2, size_t n)
str1 – 目标字符串。
str2 – 附加在目标字符串str1末尾的源字符串。
n – 需要追加的源字符串str2的字符数。例如,如果这是 5,则只有源字符串str2的前 5 个字符将附加在目标字符串str1的末尾。
返回值:该函数返回指向目标字符串str1的指针。
示例:C 中的strncat()函数
#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;}输出:
String after concatenation: This is my initial string, addDestination String str1: This is my initial string, add
正如您所看到的,在字符串str1的末尾只连接了字符串str2的 5 个字符,因为我们在 strncat()函数中将count指定为 5。
另一个需要注意的重点是这个函数返回指向目标字符串的指针,这就是为什么当我们显示 strncat()的返回值时,它与目标字符串str1相同。
