ไม่มีวิธีขยันเดียวที่สวยงามที่สุดในการ iterate words ของ C/C++ string วิธีที่อ่านง่ายที่สุดอาจถูกเรียกว่าสวยงามที่สุดสำหรับบางคน ในขณะที่ประสิทธิภาพสูงสุดสำหรับอีกบางคน ผมได้รายการ 2 วิธีที่คุณสามารถใช้เพื่อบรรลุเป้าหมายนี้ วิธีแรกคือการใช้ stringstream เพื่ออ่านคำที่คั่นด้วย spaces วิธีนี้มีข้อจำกัดเล็กน้อย แต่ทำหน้าที่ได้ดีพอหากคุณให้การตรวจสอบที่เหมาะสม ตัวอย่างเช่น
ตัวอย่างโค้ด
#include <iostream>
#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);
}
for(int i = 0; i<words.size(); i++)
cout << words[i] << endl;
}
ผลลัพธ์
Hello from the dark side