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

โปรแกรม C++ คัดลอกสตริง (Copy String)


String คืออาร์เรย์ตัวอักษรหนึ่งมิติ จบด้วย \0 สามารถคัดลอกได้ 2 วิธี: ใช้ strcpy() หรือเขียนเอง

วิธี 1: ไม่ใช้ strcpy()

#include <iostream>
using namespace std;

int main() {
    char str1[100] = "Magic";
    char str2[100];
    int i;
    for(i = 0; str1[i] != '\0'; i++)
        str2[i] = str1[i];
    str2[i] = '\0';
    cout << "The contents of str2 are: " << str2;
    return 0;
}

ผลลัพธ์

The contents of str2 are: Magic

อธิบาย

for loop คัดลอกทีละตัวอักษรจนกว่าจะเจอ \0 ใน str1 แล้วเติม \0 ท้าย str2

for(i = 0; str1[i] != '\0'; i++)
    str2[i] = str1[i];
str2[i] = '\0';
cout<<"The contents of str2 are: "<<str2;

วิธี 2: ใช้ strcpy()

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

int main() {
    char str1[100] = "Magic";
    char str2[100];
    strcpy(str2, str1);
    cout << "The contents of str2 are: " << str2;
    return 0;
}

ผลลัพธ์

The contents of str2 are: Magic

อธิบาย

strcpy(str2, str1);
cout<<"The contents of str2 are: "<<str2;

strcpy() ใน คัดลอกรวม \0 อัตโนมัติ