在 C++ 中對字串進行標記化?


第一種方法是使用 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 日

265 次檢視

開啟你的 職業生涯

透過完成課程,獲得認證

開始
廣告
© . All rights reserved.