ในโปรแกรมนี้ เราจะมาดูวิธีแยกสตริงที่คั่นด้วยเครื่องหมายจุลภาคใน C++ เราจะใส่สตริงที่มีข้อความอยู่ และคั่นด้วยเครื่องหมายจุลภาค หลังจากรันโปรแกรมนี้ มันจะแยกสตริงเหล่านั้นออกเป็นอ็อบเจกต์ประเภทเวกเตอร์
เราใช้ฟังก์ชัน getline() เพื่อแยกพวกมันออก ไวยากรณ์พื้นฐานของฟังก์ชันนี้มีลักษณะดังนี้:
getline (input_stream, string, delim)
ฟังก์ชันนี้ใช้เพื่ออ่านสตริงหรือบรรทัดจากอินพุตสตรีม
Input: Some strings "ABC,XYZ,Hello,World,25,C++" Output: Separated string ABC XYZ Hello World 25 C++
อัลกอริทึม
Step 1: Create stream from given string Step 2: While the stream is not completed Step 2.1: Take item before comma Step 2.2: Add item into a vector Step 3: Return the vector
โค้ดตัวอย่าง
#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
main() {
string my_str = "ABC,XYZ,Hello,World,25,C++";
vector<string> result;
stringstream s_stream(my_str); //create string stream from the string
while(s_stream.good()) {
string substr;
getline(s_stream, substr, ','); //get first string delimited by comma
result.push_back(substr);
}
for(int i = 0; i<result.size(); i++) { //print all splitted strings
cout << result.at(i) << endl;
}
} ผลลัพธ์
ABC XYZ Hello World 25 C++