ไม่มีวิธีที่ยอดเยี่ยมในการวนซ้ำคำของสตริง C/C++ วิธีที่อ่านง่ายที่สุดอาจเรียกได้ว่าเป็นวิธีที่สง่างามที่สุดสำหรับบางคน ในขณะที่วิธีที่มีประสิทธิภาพที่สุดสำหรับคนอื่นๆ ฉันได้ระบุ 2 วิธีที่คุณสามารถใช้เพื่อให้บรรลุสิ่งนี้ วิธีแรกคือการใช้สตริงสตรีมเพื่ออ่านคำที่คั่นด้วยช่องว่าง สิ่งนี้มีข้อ จำกัด เล็กน้อย แต่ทำงานได้ดีหากคุณให้การตรวจสอบที่เหมาะสม ตัวอย่างเช่น>
โค้ดตัวอย่าง
#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