C語言中的strncat()函式是什麼?
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":;
**訪問**:使用控制字串“%s”訪問字串,直到遇到‘\0’。
strncat( )函式
用於將一個字串的n個字元組合或連線到另一個字串中。
目標字串的長度大於源字串。
結果連線字串將位於源字串中。
語法如下:
strncat (Destination String, Source string,n);
示例
以下程式展示了strncat()函式的使用:
#include <string.h>
main ( ){
char a [30] = "Hello
";
char b [20] = "Good Morning
";
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP