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

เปรียบเทียบ strcat() และ strncat() ใน C++


ทั้ง strcat() และ strncat() เป็นฟังก์ชันสตริงที่กำหนดไว้ล่วงหน้าใน C++ รายละเอียดมีดังนี้:

strcat()

ฟังก์ชันนี้ใช้สำหรับการต่อสตริง จะนำสำเนาของสตริงต้นทางไปต่อท้ายสตริงปลายทาง และส่งคืนพอยน์เตอร์ไปยังสตริงปลายทาง ไวยากรณ์ของ strcat() มีดังนี้:

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

โปรแกรมที่สาธิตการใช้งาน strcat() มีดังนี้:

ตัวอย่าง

#include <iostream> 
#include <cstring> 
using namespace std; 

int main() { 
    char str1[20] = "Mangoes are "; 
    char str2[20] = "yellow"; 
    strcat(str1, str2); 
    cout << "The concatenated string is "<<str1; 
    return 0; 
}

ผลลัพธ์

The concatenated string is Mangoes are yellow

ในโปรแกรมนี้ นิยามสตริงสองสตริง str1 และ str2 strcat() นำเนื้อหาของ str2 ไปต่อท้าย str1 และแสดงสตริงที่ต่อแล้วด้วย cout โค้ดส่วนนี้มีดังนี้:

char str1[20] = "Mangoes are "; 
char str2[20] = "yellow"; 
strcat(str1, str2); 
cout << "The concatenated string is "<<str1;

strncat()

ฟังก์ชันนี้ก็ใช้สำหรับการต่อสตริงเหมือน strcat() แต่จะนำจำนวนตัวอักษรที่ระบุจากสตริงต้นทางไปต่อท้ายสตริงปลายทาง และส่งคืนพอยน์เตอร์ไปยังสตริงปลายทาง ไวยากรณ์ของ strncat() มีดังนี้:

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

โปรแกรมที่สาธิตการใช้งาน strcat() มีดังนี้: (หมายเหตุ: ตัวอย่างโค้ดใช้ strncat แต่หัวข้อเขียนว่า strcat)

ตัวอย่าง

#include <iostream> 
#include <cstring> 
using namespace std; 

int main() { 
    char str1[20] = "Mangoes are "; 
    char str2[20] = "yellow"; 
    strncat(str1, str2, 4); 
    cout <<"The concatenated string is "<<str1; 
    return 0; 
}

ผลลัพธ์

The concatenated string is Mangoes are yell

ในโปรแกรมนี้ นิยามสตริงสองสตริง str1 และ str2 strncat() นำเนื้อหาของ str2 ไปต่อท้าย str1 จำนวน 4 ตัวอักษร และแสดงสตริงที่ต่อแล้วด้วย cout โค้ดส่วนนี้มีดังนี้:

char str1[20] = "Mangoes are "; 
char str2[20] = "yellow"; 
strncat(str1, str2, 4); 
cout << "The concatenated string is "<<str1;