C庫函數char *strncat(char *dest, const char *src, size_t n)將 src 指向的字符串追加到 dest 指向的字符串的末尾,最多 n 個字符。
字符數組稱為字符串。
聲明
以下是數組的聲明 -
char stringname [size];
例如:char string[50];長度為 50 個字符的字符串
初始化
- 使用單字符常量 -
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
- 使用字符串常量 -
char string[10] = "Hello":;
Accessing− 有一個控製字符串 "%s" 用於訪問字符串,直到遇到“\0”。
strncat() 函數
這用於將一個字符串的 n 個字符組合或連接成另一個。
目標字符串的長度大於源字符串。
結果連接的字符串將在源字符串中。
語法如下 -
strncat (Destination String, Source string,n);
示例
以下程序顯示了 strncat() 函數的用法 -
#include <string.h>
main ( ){
char a [30] = "Hello \n";
char b [20] = "Good Morning \n";
strncat (a,b,4);
a [9] = "\0";
printf("concatenated string = %s", a);
}
輸出
執行上述程序時,會產生以下結果 -
Concatenated string = Hello Good.
讓我們看另一個例子 -
下麵給出的是使用 strncat 庫函數將 n 個字符從源字符串連接到目標字符串的 C 程序 -
#include<stdio.h>
#include<string.h>
void main(){
//Declaring source and destination strings//
char source[45],destination[50];
//Reading source string and destination string from user//
printf("Enter the source string:");
gets(source);
printf("Enter the destination string before:");
gets(destination);
//Concatenate all the above results//
destination[2]='\0';
strncat(destination,source,2);
strncat(destination,&source[4],1);
//Printing destination string//
printf("The modified destination string:");
puts(destination);
}
輸出
執行上述程序時,會產生以下結果 -
Enter the source string:Tutorials Point Enter the destination string before:Tutorials Point C Programming The modified destination string:TuTur
相關用法
- C語言 strncpy()用法及代碼示例
- C語言 strncmp()用法及代碼示例
- C語言 strnset()用法及代碼示例
- C語言 strcspn()用法及代碼示例
- C語言 strtol()用法及代碼示例
- C語言 strrchr()用法及代碼示例
- C語言 strftime()用法及代碼示例
- C語言 strtok()用法及代碼示例
- C語言 strupr()用法及代碼示例
- C語言 strlen()用法及代碼示例
- C語言 strtod()用法及代碼示例
- C語言 strspn()用法及代碼示例
- C語言 strstr()用法及代碼示例
- C語言 strcat()用法及代碼示例
- C語言 strxfrm()用法及代碼示例
- C語言 strchr()用法及代碼示例
- C語言 strrev()用法及代碼示例
- C語言 strcmpi()用法及代碼示例
- C語言 strtok()、strtok_r()用法及代碼示例
- C語言 strerror()用法及代碼示例
注:本文由純淨天空篩選整理自Bhanu Priya大神的英文原創作品 What is strncat() Function in C language?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。