บทความนี้สาธิตวิธีการแยกประโยค (string) ออกเป็นคำ (words) แยกต่างหากใน C++
ตัวอย่าง Input/Output
Input:
I am a good boy
Output:
I am a good boy
แต่ละคำจะแสดงในบรรทัดแยกกัน
วิธีการทำงาน (Algorithm)
- รับ string เข้ามา
- วนลูปอ่านทีละตัวอักขระ
- สร้างตัวแปร string สำหรับเก็บคำปัจจุบัน
- เมื่อเจอช่องว่าง (space) ให้พิมพ์คำที่สะสมไว้ แล้วล้างตัวแปรคำปัจจุบัน
- เมื่อจบลูป ให้พิมพ์คำสุดท้ายที่เหลืออยู่
ตัวอย่างโค้ดที่ 1 (แก้ไขให้ compile ได้)
#include <iostream>
#include <string>
using namespace std;
void split(string st) {
string word = "";
for (char s : st) {
if (s == ' ') {
cout << word << endl;
word = "";
} else {
word += s;
}
}
// พิมพ์คำสุดท้าย
if (!word.empty())
cout << word << endl;
}
int main() {
string st = "Blood from heaven is mortal";
cout << st << endl;
split(st);
return 0;
}
ผลลัพธ์
Blood from heaven is mortal Blood from heaven is mortal
ตัวอย่างโค้ดที่ 2: ใช้ stringstream (วิธีมาตรฐานและสะดวกกว่า)
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
vector<string> splitString(const string& str) {
vector<string> words;
stringstream ss(str);
string word;
while (ss >> word) {
words.push_back(word);
}
return words;
}
int main() {
string st = "type a text message";
cout << st << endl;
vector<string> words = splitString(st);
for (const string& w : words) {
cout << w << endl;
}
return 0;
}
ผลลัพธ์
type a text message type a text message
วิธีอื่นๆ ที่น่าสนใจ
1. ใช้ strtok (C-style)
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "Blood from heaven is mortal";
char* token = strtok(str, " ");
while (token != nullptr) {
cout << token << endl;
token = strtok(nullptr, " ");
}
return 0;
}
⚠️ strtok จะแก้ไข string ต้นฉบับ และไม่ thread-safe
2. ใช้ regex (C++11)
#include <iostream>
#include <string>
#include <regex>
#include <vector>
using namespace std;
int main() {
string str = "Blood from heaven is mortal";
regex re("\\S+"); // non-whitespace sequences
sregex_token_iterator it(str.begin(), str.end(), re), end;
vector<string> words(it, end);
for (const auto& w : words) cout << w << endl;
return 0;
}
สรุปการเปรียบเทียบ
| วิธี | ข้อดี | ข้อเสีย |
|---|---|---|
| Manual loop | ควบคุมได้ละเอียด ไม่ต้อง include เพิ่ม | เขียนโค้ดมากกว่า |
| stringstream | มาตรฐาน อ่านง่าย จัดการ whitespace หลายตัวได้ | ช้ากว่าเล็กน้อย |
| strtok | รวดเร็ว | แก้ไข string ต้นฉบับ ไม่ thread-safe |
| regex | ยืดหยุ่น รองรับ pattern ซับซ้อน | ช้าที่สุด |