ความหมาย
strncat() นำต่อ (concatenate) string ต้นทาง (src) ไปยัง string ปลายทาง (dest) จำนวน n ตัวอักษร
Prototype
char *strncat(char *dest, const char *src, size_t n);
พารามิเตอร์
- dest - string ปลายทาง (ต้องมีพื้นที่เพียงพอ)
- src - string ต้นทาง
- n - จำนวนตัวอักษรสูงสุดที่จะนำต่อ
คืนค่า
Pointer ไปยัง dest (string ที่ต่อแล้ว)
เงื่อนไข
- dest ต้องมีขนาดพอรองรับ string เดิม + n ตัวอักษร + null terminator
- ผลลัพธ์เก็บอยู่ใน dest
ตัวอย่างโปรแกรมที่ 1: ต่อ 4 ตัวอักษรแรก
#include <stdio.h>
#include <string.h>
int main() {
char a[30] = "Hello ";
char b[20] = "Good Morning";
strncat(a, b, 4); // ต่อ 4 ตัวแรกของ b -> "Good"
printf("string ที่ต่อแล้ว = %s\\n", a);
return 0;
}ผลลัพธ์
string ที่ต่อแล้ว = Hello Good
ตัวอย่างโปรแกรมที่ 2: ต่อ string แบบกำหนดตำแหน่ง
#include <stdio.h>
#include <string.h>
int main() {
char source[45], destination[50];
printf("ป้อน source string: ");
fgets(source, sizeof(source), stdin);
source[strcspn(source, "\\n")] = '\\0';
printf("ป้อน destination string: ");
fgets(destination, sizeof(destination), stdin);
destination[strcspn(destination, "\\n")] = '\\0';
// ตัด destination ให้เหลือ 2 ตัวแรก
destination[2] = '\\0';
// ต่อ 2 ตัวแรกของ source
strncat(destination, source, 2);
// ต่อ 1 ตัวจาก source ตำแหน่งที่ 4 (index 4)
strncat(destination, &source[4], 1);
printf("destination ที่แก้ไขแล้ว: %s\\n", destination);
return 0;
}ผลลัพธ์ตัวอย่าง
ป้อน source string: Tutorials Point ป้อน destination string: Tutorials Point C Programming destination ที่แก้ไขแล้ว: TuTur
คำอธิบาย: destination เริ่มต้น "Tu" (ตัดที่ index 2) -> ต่อ "Tu" จาก source -> "TuTu" -> ต่อ "r" (source[4]) -> "TuTur"
ความแตกต่าง strcat vs strncat
| ฟังก์ชัน | การทำงาน | ความปลอดภัย |
|---|---|---|
| strcat | ต่อ string ทั้งหมด | อันตราย หาก dest ไม่พอ |
| strncat | ต่อสูงสุด n ตัวอักษร | ปลอดภัยกว่า (ป้องกัน buffer overflow) |
หมายเหตุ
- ต้อง include
<string.h> - strncat จะเติม null terminator ให้อัตโนมัติ
- ควรตรวจสอบขนาด buffer ก่อนใช้