如何在 C++ 中对一个字符串进行标记化
    
    Jinku Hu
    2023年10月12日
    
    C++
    C++ String
    
- 
          
            使用 find和substr函数在 C++ 中对一个字符串进行标记化
- 
          
            在 C++ 中使用 std::stringstream和getline函数标记字符串
- 
          
            在 C++ 中使用 istringstream和copy算法对一个字符串进行标记化
 
本文将介绍几种在 C++ 中对字符串进行标记化的方法。
使用 find 和 substr 函数在 C++ 中对一个字符串进行标记化
    
std::string 类有一个内置的 find 函数,用于搜索给定字符串对象中的字符序列。find 函数返回在字符串中找到的第一个字符的位置,如果没有找到则返回 npos。find 函数的调用插入到 if 语句中,对字符串进行遍历,直到提取出最后一个字符串标记。
请注意,用户可以指定任何字符串类型的定界符,并将其传递给 find 方法。每次迭代时,标记都会被推送到字符串的向量中,并通过 erase() 函数删除已处理的部分。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
string text = "Think you are escaping and run into yourself.";
int main() {
  string delim = " ";
  vector<string> words{};
  size_t pos = 0;
  while ((pos = text.find(delim)) != string::npos) {
    words.push_back(text.substr(0, pos));
    text.erase(0, pos + delim.length());
  }
  if (!text.empty()) words.push_back(text.substr(0, pos));
  for (const auto &str : words) {
    cout << str << endl;
  }
  return EXIT_SUCCESS;
}
输出:
Think
you
are
escaping
and
run
into
yourself.
在 C++ 中使用 std::stringstream 和 getline 函数标记字符串
stringstream 可以用来提取一个要处理的字符串,并使用 getline 提取标记,直到找到给定的定界符。注意,这个方法只适用于单字符定界符。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::istringstream;
using std::string;
using std::stringstream;
using std::vector;
int main() {
  string text = "Think you are escaping and run into yourself.";
  char del = ' ';
  vector<string> words{};
  stringstream sstream(text);
  string word;
  while (std::getline(sstream, word, del)) words.push_back(word);
  for (const auto &str : words) {
    cout << str << endl;
  }
  return EXIT_SUCCESS;
}
输出:
Think
you
are
escaping
and
run
into
yourself.
在 C++ 中使用 istringstream 和 copy 算法对一个字符串进行标记化
另外,也可以使用 <algorithm> 头文件中的 copy 函数,在空白字符定界符上提取字符串标记。在下面的例子中,我们只迭代并将标记流到标准输出。为了用 copy 方法处理字符串,我们将其插入 istringstream 中,并利用其迭代器。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::istringstream;
using std::string;
using std::stringstream;
using std::vector;
int main() {
  string text = "Think you are escaping and run into yourself.";
  string delim = " ";
  vector<string> words{};
  istringstream iss(text);
  copy(std::istream_iterator<string>(iss), std::istream_iterator<string>(),
       std::ostream_iterator<string>(cout, "\n"));
  return EXIT_SUCCESS;
}
输出:
Think
you
are
escaping
and
run
into
yourself.
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Jinku Hu
    
