C++ 使用多个字符串分隔符拆分字符串
假设我有像绳子一样的东西C++ 使用多个字符串分隔符拆分字符串,c++,boost,C++,Boost,假设我有像绳子一样的东西 Harry potter was written by J. K. Rowling 如何使用拆分字符串为和 >以< /代码>为定界符,在C++(?)/P>中得到矢量结果。 我知道拆分使用多个字符,但不使用多个字符串。如果使用c++11和clang,有一种使用正则表达式字符串标记器的解决方案: #include <fstream> #include <iostream> #include <algorithm> #include
Harry potter was written by J. K. Rowling
<>如何使用<代码>拆分字符串为和我知道拆分使用多个字符,但不使用多个字符串。如果使用c++11和clang,有一种使用正则表达式字符串标记器的解决方案:
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <regex>
int main()
{
std::string text = " Harry potter was written by J. K. Rowling.";
std::regex ws_re("(was)|(by)");
std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
遗憾的是,gcc4.8没有完全集成正则表达式。但clang确实正确地编译和链接了这一点 蛮力方法,不是boost,没有c++11,非常欢迎优化:
/** Split the string s by the delimiters, place the result in the
outgoing vector result */
void split(const std::string& s, const std::vector<std::string>& delims,
std::vector<std::string>& result)
{
// split the string into words
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> splits(begin, end);
// then append the words together, except if they are delimiter
std::string current;
for(int i=0; i<splits.size(); i++)
{
if(std::find(delims.begin(), delims.end(), splits[i]) != delims.end())
{
result.push_back(current);
current = "";
}
else
{
current += splits[i] + " " ;
}
}
result.push_back(current.substr(0, current.size() - 1));
}
/**按分隔符拆分字符串,将结果放入
输出向量结果*/
无效拆分(常量std::string&s、常量std::vector&delims、,
标准:向量和结果)
{
//将字符串拆分为单词
标准::stringstream ss(s);
std::istream_迭代器begin(ss);
std::istream_迭代器端;
std::向量拆分(开始、结束);
//然后将单词附加在一起,除非它们是分隔符
串电流;
对于(int i=0;i关于regex令牌迭代器如何?:在可能的情况下我尽量不使用regex,但是如果可能的话,一个regex的答案对于给定的示例也会有帮助。BOOST在那里如果你可以使用BOOST举个例子,那么它也会有帮助。生成的令牌末尾和开头的空格不正确。例如,对于我得到的示例“哈利波特”,“书面”,“J.K.罗琳”代替“哈利波特”,“书面”,“J.K.罗琳”。@tgmath谢谢,修正了!
/** Split the string s by the delimiters, place the result in the
outgoing vector result */
void split(const std::string& s, const std::vector<std::string>& delims,
std::vector<std::string>& result)
{
// split the string into words
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> splits(begin, end);
// then append the words together, except if they are delimiter
std::string current;
for(int i=0; i<splits.size(); i++)
{
if(std::find(delims.begin(), delims.end(), splits[i]) != delims.end())
{
result.push_back(current);
current = "";
}
else
{
current += splits[i] + " " ;
}
}
result.push_back(current.substr(0, current.size() - 1));
}