Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ฟังก์ชัน strncat() ต่อสตริง n ตัวอักษรใน C


strcat() - ต่อสตริงทั้งหมด

char *strcat(char *dest, const char *src);

ต่อ src เข้า dest ทั้งหมด dest ต้องมีพื้นที่พอ

strncat() - ต่อสตริงแค่ n ตัวอักษรแรก

char *strncat(char *dest, const char *src, size_t n);

ต่อได้สูงสุด n ตัวอักษรจาก src เข้า dest

ตัวอย่างที่ 1: strcat()

char a[50] = "Hello";
char b[20] = "Good Morning";
strcat(a, b);
// a = "HelloGood Morning"

ตัวอย่างที่ 2: strncat() ต่อ 4 ตัวอักษร

char a[30] = "Hello";
char b[20] = "Good Morning";
strncat(a, b, 4);
a[9] = '\0';
// a = "Hello Good"

ตัวอย่างที่ 3: ต่อบางส่วนจาก source

#include <stdio.h>
#include <string.h>
int main() {
    char source[45], dest[50];
    
    printf("Source: "); gets(source);
    printf("Dest before: "); gets(dest);
    
    dest[2] = '\0';           // ตัด dest ให้เหลือ 2 ตัว
    strncat(dest, source, 2); // ต่อ 2 ตัวแรกของ source
    strncat(dest, &source[4], 1); // ต่อตัวที่ 5 ของ source
    
    printf("Modified dest: %s\n", dest);
    return 0;
}

ผลลัพธ์

Source: TutorialPoint
Dest before: C Programming
Modified dest: C Tur