ปัญหา
เขียนโปรแกรม C เพื่อเชื่อมอักขระ n ตัวจากสตริงต้นทางไปยังสตริงปลายทางโดยใช้ฟังก์ชันไลบรารี strncat
วิธีแก้ปัญหา
ฟังก์ชัน 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