Java有一个方便的split方法:
String str = "The quick brown fox";
String[] results = str.split(" ");
在 C++ 中有没有一种简单的方法可以做到这一点?
最佳答案
Boost tokenizer类可以使这类事情变得非常简单:
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int, char**)
{
string text = "token, test string";
char_separator<char> sep(", ");
tokenizer< char_separator<char> > tokens(text, sep);
BOOST_FOREACH (const string& t, tokens) {
cout << t << "." << endl;
}
}
针对 C++11 更新:
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main(int, char**)
{
string text = "token, test string";
char_separator<char> sep(", ");
tokenizer<char_separator<char>> tokens(text, sep);
for (const auto& t : tokens) {
cout << t << "." << endl;
}
}
关于c++ - 如何在 C++ 中标记字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5751031/