# Concatenation

&#x20;    Concatenation คือการนำ sting เข้ามาต่อเข้าด้วยกันซึ่งสามารถทำได้สองวิธีคือ

{% tabs %}
{% tab title="แบบที่ 1" %}

```cpp
//ใช้เครื่องหมาย +
#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; 
} 
```

{% endtab %}

{% tab title="แบบที่ 2" %}

```cpp
//ใช้คำสั่ง string.append()
#include <iostream> 
#include <string.h> 
using namespace std;

int main() 
{ string M = "Hello ";
  string N = "world";
  string O = M.append(N);
  cout << O <<endl;
  
	return 0; 
} 
```

{% endtab %}
{% endtabs %}

![](/files/-MSaoDQLdRp9qU0B1BSR)

จากผลการรันทั้งสองแบบจะเห็นได้ว่าทั้งสองแบบให้ผลแบบเดียวกัน ดังนั้นการเลือกใช้จะขึ้นอยู่กับความถนัดของแต่ละคนว่าจะเลือกใช้แบบไหน

{% hint style="danger" %}
ข้อควรระวัง การนำ string ต่อกับตัวเลขไม่สามารถทำได้ถ้าประเภทของตัวเลขนั้นไม่ได้เป็นประเภท string
{% endhint %}

```cpp
#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; 
} 
```

![](/files/-MSaqA7pDXT_IfXtOm4F)

ถ้าต้องการนำ sting ต่อกับตัวแปรประเภทอื่นๆให้ใช้คำสั่ง to\_string

```cpp
#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; 
} 
```

![](/files/-MSaqMJmkum2DQDa0uOP)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aic-eec.com/c-c++-for-embedded-programming/string-in-c++/concatenation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
