如何在 C++ 中对一个字符串进行标记化
本文将介绍几种在 C++ 中对字符串进行标记化的方法。
使用 find
和 substr
函数在 C++ 中对一个字符串进行标记化
std::string
类有一个内置的 find
函数,用于搜索给定字符串对象中的字符序列。find
函数返回在字符串中找到的第一个字符的位置,如果没有找到则返回 npos
。find
函数的调用插入到 if
语句中,对字符串进行遍历,直到提取出最后一个字符串标记。
请注意,用户可以指定任何字符串类型的定界符,并将其传递给 find
方法。每次迭代时,标记都会被推送到字符串的向量中,并通过 erase()
函数删除已处理的部分。
#include <iostream>#include <string>#include <iterator>#include <vector>#include <algorithm>using std::cout; using std::cin;
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 <iostream>#include <string>#include <sstream>#include <iterator>#include <vector>#include <algorithm>using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::istringstream;
using std::stringstream;
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 <iostream>#include <string>#include <sstream>#include <iterator>#include <vector>#include <algorithm>using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::istringstream;
using std::stringstream;
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.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。