Phần này sẽ xem cách tách chuỗi (tokenize) trong C++. Trong C có thể dùng strtok() cho mảng ký tự. Ở đây có lớp string. Ta sẽ xem cách cắt chuỗi dùng ký tự phân tách (delimiter) từ chuỗi đó.
Để dùng tính năng C++, phải chuyển chuỗi thành string stream. Sau đó dùng hàm getline() để thực hiện. getline() nhận string stream, một chuỗi khác để chứa kết quả, và delimiter để dừng luồng quét.
Xem ví dụ sau để hiểu hàm hoạt động như thế nào.
Ví dụ mã
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int main() {
string my_string = "Hello,World,India,Earth,London";
stringstream ss(my_string); // chuyển my_string thành string stream
vector<string> tokens;
string temp_str;
while(getline(ss, temp_str, ',')){ // dùng dấu phẩy làm delimiter
tokens.push_back(temp_str);
}
for(int i = 0; i < tokens.size(); i++) {
cout << tokens[i] << endl;
}
}
Kết quả
Hello World India Earth London