ตัวอย่างโค้ดภาษาซี สำหรับการต่อข้อความหรือต่อคำ โดยการใช้ strcat
สามารถทำได้ดังนี้
ตัวอย่างโค้ด
/***************************************************
* Author : CS Developers
* Author URI: https://www.comscidev.com
* Facebook : https://www.facebook.com/CSDevelopers
***************************************************/
#include <stdio.h>
#include <string.h>
int main()
{
char str[100] = " CS ";
strcat(str, "Developers ");
strcat(str, "URL: ");
strcat(str, "https://www.comscidev.com/ ");
printf("\n%s\n", str);
return 0;
}
อธิบายเพิ่มเติม
- จะต้อง
include <string.h>
ถึงจะใช้งานstrcat
ได้ - การใช้งาน
strcat
จะต้องส่ง parameter 2 ค่าเข้าไป ตัวแรกจะเป็นข้อความหลัก และตัวที่ 2 จะเป็นข้อความที่ต้องการนำไปต่อท้ายข้อความหลัก strcat("CS ", "Developers");
เมื่อแสดงผลจะได้ CS Developers
ตัวอย่างโค้ด 2
/***************************************************
* Author : CS Developers
* Author URI: https://www.comscidev.com
* Facebook : https://www.facebook.com/CSDevelopers
***************************************************/
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
strcpy(str, " CS ");
strcat(str, "Developers ");
strcat(str, "URL: ");
strcat(str, "https://www.comscidev.com/ ");
printf("\n%s\n", str);
return 0;
}
อธิบายเพิ่มเติมสำหรับโค้ด 2
- ไม่ได้กำหนดค่าเริ่มต้นให้ข้อความ
- ใช้
strcpy
เพื่อกำหนดค่าเริ่มต้นให้กับตัวแปรstr
- ใช้
strcat
เพิ่มค่าข้อความเข้าไปต่อท้าย
แสดงผล
