使用 C++ 迭代字串中單詞的最優雅方式


沒有一種優雅的方式來迭代 C/C++ 字串中的單詞,對一些人來說最易讀的方式可能是最優雅的,而對另一些人來說可能是最高效的。我列出了你可以用來實現這一點的 2 種方法。第一種方法是使用 stringstream 來讀取以空格分隔的單詞。這有點侷限,但如果你提供適當的檢查,它可以很好地完成這個任務。例如,>

示例程式碼

 即時演示

#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

更新於: 30-Jul-2019

110 次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.