วิธีแรกคือการใช้สตริงสตรีมเพื่ออ่านคำที่คั่นด้วยการเว้นวรรค สิ่งนี้มีข้อ จำกัด เล็กน้อย แต่ทำงานได้ดีหากคุณให้การตรวจสอบที่เหมาะสม
ตัวอย่าง
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str("Hello from the dark side");
string tmp; // A string to store the word on each iteration.
stringstream str_strm(str);
vector<string> words; // Create vector to hold our words
while (str_strm >> tmp) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
} ตัวอย่าง
อีกวิธีหนึ่งคือการจัดเตรียมตัวคั่นแบบกำหนดเองเพื่อแยกสตริงโดยใช้ฟังก์ชัน getline -
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
std::stringstream str_strm("Hello from the dark side");
std::string tmp;
vector<string> words;
char delim = ' '; // Ddefine the delimiter to split by
while (std::getline(str_strm, tmp, delim)) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
}