Concatenation
Put your sting together
Concatenation คือการนำ sting เข้ามาต่อเข้าด้วยกันซึ่งสามารถทำได้สองวิธีคือ
//ใช้เครื่องหมาย +
#include <iostream>
#include <string.h>
using namespace std;
int main()
{ string M = "Hello ";
string N = "world";
string O = M+N;
cout << O <<endl;
return 0;
}

จากผลการรันทั้งสองแบบจะเห็นได้ว่าทั้งสองแบบให้ผลแบบเดียวกัน ดังนั้นการเลือกใช้จะขึ้นอยู่กับความถนัดของแต่ละคนว่าจะเลือกใช้แบบไหน
ข้อควรระวัง การนำ string ต่อกับตัวเลขไม่สามารถทำได้ถ้าประเภทของตัวเลขนั้นไม่ได้เป็นประเภท string
#include <iostream>
#include <string.h>
using namespace std;
int main()
{ string M = "Number is ";
int N = 69;
string O = M+N;
cout << O <<endl;
return 0;
}

ถ้าต้องการนำ sting ต่อกับตัวแปรประเภทอื่นๆให้ใช้คำสั่ง to_string
#include <iostream>
#include <string.h>
using namespace std;
int main()
{ string M = "Number is ";
int N = 69;
string O = M+to_string(N); //cast an int to string
cout << O <<endl;
return 0;
}

Last updated
Was this helpful?