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

strdup() และ strdndup() ใน C/C++


strdup()

ฟังก์ชัน strdup() ใช้เพื่อทำซ้ำสตริง ส่งคืนตัวชี้ไปยังสตริงไบต์ที่สิ้นสุดด้วยค่า null

นี่คือไวยากรณ์ของ strdup() ในภาษา C

char *strdup(const char *string);

นี่คือตัวอย่าง strdup() ในภาษา C

ตัวอย่าง

#include <stdio.h>
#include<string.h>
int main() {
   char *str = "Helloworld";
   char *result;
   result = strdup(str);
   printf("The string : %s", result);
   return 0;
}

ผลลัพธ์

The string : Helloworld

strndup()

ฟังก์ชัน strndup ทำงานคล้ายกับฟังก์ชัน strndup() ฟังก์ชันนี้ทำซ้ำสตริงที่ขนาดไบต์สูงสุด เช่น ขนาดที่กำหนดในฟังก์ชัน นอกจากนี้ยังส่งกลับตัวชี้ไปยังสตริงไบต์ที่สิ้นสุดด้วยค่า null

นี่คือไวยากรณ์ของ strndup() ในภาษา C

char *strndup(const char *string , size_t size);

นี่คือตัวอย่าง strndup() ในภาษา C

ตัวอย่าง

#include <stdio.h>
#include<string.h>
int main() {
   char *str = "Helloworld";
   char *result;
   result = strndup(str, 3);
   printf("The string : %s", result);
   return 0;
}

ผลลัพธ์

The string : Hel