將源字串 n 個字元連線到 C 中目標字串
問題
編寫一個 C 程式,使用 strncat 庫函式將 n 個字元從源字串連線到目標字串
解決方案
strcat 函式
此函式用於組合或連線兩個字串。
目標字串的長度必須大於源字串。
最終的連線字串位於源字串中。
語法
strcat (Destination String, Source string);
示例 1
#include <string.h>
main(){
char a[50] = "Hello";
char b[20] = "Good Morning";
clrscr ( );
strcat (a,b);
printf("concatenated string = %s", a);
getch ( );
}輸出
Concatenated string = Hello Good Morning
strncat 函式
此函式用於將一個字串的 n 個字元組合或連線到另一個字串。
目標字串的長度必須大於源字串。
最終的連線字串位於目標字串中。
語法
strncat (Destination String, Source string,n);
示例 2
#include <string.h>
main ( ){
char a [30] = "Hello";
char b [20] = "Good Morning";
clrscr ( );
strncat (a,b,4);
a [9] = ‘\0’;
printf("concatenated string = %s", a);
getch ( );
}輸出
Concatenated string = Hello Good.
示例 3
#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 :TutorialPoint Enter the destination string before :C Programming The modified destination string :C Tur
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP