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

โปรแกรม C++ ต่อสตริง (String Concatenation)


Concatenation คือการต่อสตริง 2 ตัวเข้าด้วยกัน ตัวอย่าง: "Mangoes are" + "tasty" = "Mangoes are tasty"

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

int main() {
    char str1[100] = "Hi...";
    char str2[100] = "How are you";
    int i, j;
    cout << "String 1: " << str1 << endl;
    cout << "String 2: " << str2 << endl;
    for(i = 0; str1[i] != '\0'; ++i);
    j = 0;
    while(str2[j] != '\0') {
        str1[i] = str2[j];
        i++;
        j++;
    }
    str1[i] = '\0';
    cout << "String after concatenation: " << str1;
    return 0;
}

ผลลัพธ์

String 1: Hi...
String 2: How are you
String after concatenation: Hi...How are you

อธิบายขั้นตอน

1. for loop หาตำแหน่ง \0 ของ str1 (i จะเป็น index ของ \0):

for(i = 0; str1[i] != '\0'; ++i);

2. while loop คัดลอก str2 ไปต่อท้าย str1 ตั้งแต่ตำแหน่ง i:

j = 0;
while(str2[j] != '\0') {
    str1[i] = str2[j];
    i++;
    j++;
}

3. ใส่ \0 ท้าย str1 แล้วแสดงผล:

str1[i] = '\0';
cout<<"String after concatenation: "<<str1;