Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธี iterate คำใน C/C++ String ที่ elegant ที่สุด


ไม่มี "วิธีเดียวที่ elegant ที่สุด" ขึ้นอยู่กับเป้าหมาย (readability vs performance) นี่คือ 2 วิธีหลัก:

วิธีที่ 1: stringstream (อ่านคั่นด้วย whitespace)

#include <vector>
#include <string>
#include <sstream>
using namespace std;

int main() {
    string str("Hello from the dark side");
    string tmp;
    stringstream str_strm(str);
    vector<string> words;
    while (str_strm >> tmp) {
        // ตรวจสอบ tmp, strip punctuation
        words.push_back(tmp);
    }
}

วิธีที่ 2: getline กับ custom delimiter

#include <vector>
#include <string>
#include <sstream>
using namespace std;

int main() {
    stringstream str_strm("Hello from the dark side");
    string tmp;
    vector<string> words;
    char delim = ' ';
    while (getline(str_strm, tmp, delim)) {
        // ตรวจสอบ tmp, strip punctuation
        words.push_back(tmp);
    }
}

วิธีที่ 1 ใช้ operator>> แยก whitespace อัตโนมัติ วิธีที่ 2 ระบุ delimiter เองได้ (comma, pipe, etc.)