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

Tokenizing a string in C++ (การแบ่งสตริงเป็นโทเคน)


ในส่วนนี้ เราจะดูวิธี tokenize strings ใน C++ ใน C เราสามารถใช้ฟังก์ชัน strtok() สำหรับ character array ได้ ที่นี่เรามี string class ตอนนี้เราจะดูวิธีตัด string โดยใช้ delimiter จาก string นั้น

เพื่อใช้ C++ feature เราต้องแปลง string เป็น string stream แล้วใช้ getline() function ก็สามารถทำได้ ฟังก์ชัน getline() รับ string stream, string อีกตัวหนึ่งเพื่อส่ง output, และ delimiter เพื่อหยุด stream จากการสแกน

ลองดูตัวอย่างต่อไปนี้เพื่อเข้าใจว่าฟังก์ชันทำงานอย่างไร

ตัวอย่างโค้ด

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main() {
    string my_string = "Hello,World,India,Earth,London";
    stringstream ss(my_string); //convert my_string into string stream
    vector<string> tokens;
    string temp_str;
    while(getline(ss, temp_str, ',')){ //use comma as delim for cutting string
        tokens.push_back(temp_str);
    }
    for(int i = 0; i < tokens.size(); i++) {
        cout << tokens[i] << endl;
    }
}

ผลลัพธ์

Hello
World
India
Earth
London