# Split

&#x20;         หลังจากการนำ string มาต่อกัน การแบ่ง string ออกจากกันก็มีความสำคัญเช่นกัน ซึ่งสามารถนำไปประยุกต์ใช้กับอุปกรณ์ไมโครคอนโทรลเลอร์ ที่รับค่ามาจากหลายๆที่และส่งออกไปเป็นข้อความข้อความเดียวแล้วจึงนำไปตัดเป็นส่วนๆเพื่อวิเคราะห์

```cpp
// C++ program to print words in a sentence
#include <iostream> 
#include <string.h> 
using namespace std;


void split(string str,string store[])
{
	string word = "";
  int a = 0;
	for (auto x : str) 
	{
		if (x == ' ') // split when see spacebar
		{
			cout << word << endl;
      store[a] = word;
      a++;
			word = "";
		}
		else {
			word = word + x;
		}
	}
  store[a] = word;
	cout << word <<"\n"<< endl;
}

// Driver code
int main()
{
	string str = "A:8 C:9 J:7 K:9";
  string store[5];
	split(str,store);
	//print store value
  /*for (int x=0; x<=5;x++){
     cout<<store[x]<<endl;
  }*/
	return 0;
}

```

![ผลการตัดข้อความด้วย spacebar](https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MClo3nC-1US0rbK8Qau%2F-MTAGjjOXBgjaa7K9P2-%2F-MTAPoXbbZQOFyj17714%2Fimage.png?alt=media\&token=3f1818fe-4fcc-42ea-b2b3-d7a3d49303ae)

จากตัวอย่างด้านบน เป็นตัวอย่างการแบ่งข้อความเป็นส่วนๆเมื่อเจอ spacebar ในข้อความเราสามารถเปลี่ยนให้แบ่งข้อความด้วยอย่างอืนได้เช่นเครื่องหมาย  " : "&#x20;

```cpp

		if (x == ':') // split when see colon
		{
			cout << word << endl;
      store[a] = word;
      a++;
			word = "";
		}
		else {
			word = word + x;
		}
	
```

![ผลการตัดข้อความด้วย " : "](https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MClo3nC-1US0rbK8Qau%2F-MTAGjjOXBgjaa7K9P2-%2F-MTAQ9kBqjVKVynkSZXv%2Fimage.png?alt=media\&token=b26683be-74ee-4658-918f-660026527030)

{% hint style="info" %}
การระบุ format ของข้อความแบบนี้สามารถพบเห็นได้กับไฟล์ประเภท .csv, .json&#x20;
{% endhint %}

reference: [Geeksforgeeks](https://www.geeksforgeeks.org/split-a-sentence-into-words-in-cpp/)
