用 C++ 标记化字符串?


第一种方式是用一个字符串流来读取以空格分隔的单词。这种方式有点局限,但是如果你进行适当的检查,它可以完成这项任务。 

示例

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

更新于: 11-Feb-2020

265 次浏览

开始你的 职业

完成课程后获得认证

开始吧
广告
© . All rights reserved.