迭代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日

2K+ 次瀏覽

助力您的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.