Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การแยกประโยคเป็นคำ (Split String into Words) ใน C++

บทความนี้สาธิตวิธีการแยกประโยค (string) ออกเป็นคำ (words) แยกต่างหากใน C++

ตัวอย่าง Input/Output

Input:

I am a good boy

Output:

I
am
a
good
boy

แต่ละคำจะแสดงในบรรทัดแยกกัน

วิธีการทำงาน (Algorithm)

  1. รับ string เข้ามา
  2. วนลูปอ่านทีละตัวอักขระ
  3. สร้างตัวแปร string สำหรับเก็บคำปัจจุบัน
  4. เมื่อเจอช่องว่าง (space) ให้พิมพ์คำที่สะสมไว้ แล้วล้างตัวแปรคำปัจจุบัน
  5. เมื่อจบลูป ให้พิมพ์คำสุดท้ายที่เหลืออยู่

ตัวอย่างโค้ดที่ 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 ซับซ้อนช้าที่สุด