# String in C++

&#x20;    String คือประเภทตัวแปรประเภทหนึ่งไว้สำหรับเก็บข้อมูลประเภท "ข้อความ" ข้อมูลใดๆก็ตามที่เก็บไว้ในตัวแปร string จะถูกนับว่าเป็นตัวอักษรทั้งหมดแม้ว่าข้อมูลที่ใส่ภายในจะเป็นตัวเลขก็ตาม

การใช้ตัวแปร string&#x20;

1.จะต้องมีการ include string.h ก่อนเสมอ

```cpp
#include <string.h>
```

2.การประกาศตัวแปร string

```cpp
string A = "Hello";
string B = "";
string C;
```

string นั้นประกอบไปด้วย char หลายๆตัวต่อๆกันดังนั้นการใช้งาน string จะเหมือนกับการใช้งาน Array

{% tabs %}
{% tab title="Ex1" %}

```cpp
#include <iostream> 
#include <string.h> 
using namespace std;

int main() 
{ string M = "Hello";
  cout<<M[0]<<endl;
  cout<<M[1]<<endl;
  cout<<M[2]<<endl;
  cout<<M[3]<<endl;
  cout<<M[4]<<endl;
	return 0; 
} 
```

ผลการรันตัวอย่าง

![](https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MClo3nC-1US0rbK8Qau%2F-MSae3YSR3uOqDAz_H2S%2F-MSal2RdY5vbIgvFlUoN%2Fimage.png?alt=media\&token=323928a9-6911-4831-9a1f-ab5528cc1b91)
{% endtab %}

{% tab title="Ex2" %}

```cpp
#include <iostream> 
#include <string.h> 
using namespace std;

int main() 
{ string M = "Hello";
  for(int i=0;i<=4;i++){
  cout<<M[i]<<endl;
  }
	return 0; 
} 
```

{% endtab %}
{% endtabs %}

จากตัวอย่างด้านบนจะเห็นได้ว่าเราสามารถเข้าถึงตัวอักษรทุกตัวได้ตามลำดับของ string ทำให้เราสามารถเข้าไปเปลี่ยนค่าของแต่ละตำแหน่งทีละตัวได้

```cpp
#include <iostream> 
#include <string.h> 
using namespace std;

int main() 
{ string M = "Hello";
  cout<<M<<endl;

  M[0]='J';//change [0] to J
  cout<<M<<endl;

  M[4]='y';//change [4] to y
  cout<<M<<endl;
	return 0; 
} 
```

![](https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MClo3nC-1US0rbK8Qau%2F-MSae3YSR3uOqDAz_H2S%2F-MSalzlxuydIJzBoxEUN%2Fimage.png?alt=media\&token=0b0211f8-efd8-410a-9df1-fdd80f66d230)


---

# 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++.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.
