遍歷 C/C++ 字串中最優雅的方式


沒有一種優雅的方法可以遍歷 C/C++ 字串的單詞。對某些人來說,最容易讀懂的方式可以稱為最優雅的方式,而對另一些人來說,效能最高的方式可以稱為最優雅的方式。我已經列出了 2 個可以用來實現這一目標的方法。第一種方法是使用 stringstream 讀取用空格分隔的單詞。這有一些限制,但如果你提供適當的檢查,它可以很好地完成這項任務。 

示例

#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);
    }
}

更新於: 2020 年 2 月 11 日

2000 多次瀏覽

啟動你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.