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

ฟังก์ชัน strncpy() ในภาษา C: คัดลอก String จำนวน n ตัวอักษร

strncpy() = คัดลอก n ตัวอักษรจาก source ไป destination หาก source สั้นกว่า n จะเติม null bytes

Syntax

strncpy(dest, src, n);

โปรแกรมตัวอย่าง

#include <stdio.h>
#include <string.h>
main() {
    char a[50], b[50];
    printf("Enter a string: ");
    gets(a);
    strncpy(b, a, 3);
    b[3] = '\0'; // ต้องใส่ null terminator เอง
    printf("Copied string = %s\n", b);
}

ผลลัพธ์

Enter a string: Hello
Copied string = Hel

การใช้งาน: ดึง substring


char result[10], s1[15] = "Jan 10 2010";
strncpy(result, &s1[4], 2); // copy 2 chars จาก index 4
result[2] = '\0';
// result = "10"

โปรแกรมเพิ่มเติม: คัดลอกหลายส่วนแล้วต่อกัน (strcat)

#include <stdio.h>
#include <string.h>
void main() {
    char source[45], dest1[10], dest2[10], dest3[10];
    printf("Enter source string: ");
    gets(source);
    strncpy(dest1, source, 2); dest1[2] = '\0';
    strncpy(dest2, &source[8], 1); dest2[1] = '\0';
    strncpy(dest3, &source[12], 1); dest3[1] = '\0';
    strcat(dest1, dest2);
    strcat(dest1, dest3);
    printf("Modified: %s\n", dest1);
}

ผลลัพธ์

Enter source string: Tutorials Point
Modified: Tusi