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