C++ C++;将字符串拆分为另一个字符串作为一个整体
我想按C++ C++;将字符串拆分为另一个字符串作为一个整体,c++,string,c++11,boost,C++,String,C++11,Boost,我想按和的任何出现来拆分字符串 首先,我必须明确指出,我不打算使用任何regex作为分隔符 我运行以下代码: #include <iostream> #include <regex> #include <boost/algorithm/string.hpp> int main() { std::vector<std::string> results; std::string text= "Alexievich, S
和
的任何出现来拆分字符串
首先,我必须明确指出,我不打算使用任何regex
作为分隔符
我运行以下代码:
#include <iostream>
#include <regex>
#include <boost/algorithm/string.hpp>
int main()
{
std::vector<std::string> results;
std::string text=
"Alexievich, Svetlana and Lindahl,Tomas and Campbell,William";
boost::split(
results,
text,
boost::is_any_of(" and "),
boost::token_compress_off
);
for(auto result:results)
{
std::cout<<result<<"\n";
}
return 0;
}
似乎分隔符中的每个字符都单独起作用,而我需要将整个和
作为分隔符
请不要链接到,除非您确定它适用于我的案例。传统方式:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> results;
std::string text=
"Alexievich, Svetlana and Lindahl,Tomas and Campbell,William";
size_t pos = 0;
for (;;) {
size_t next = text.find("and", pos);
results.push_back(text.substr(pos, next - pos));
if (next == std::string::npos) break;
pos = next + 3;
}
for(auto result:results)
{
std::cout<<result<<"\n";
}
return 0;
}
#包括
#包括
#包括
int main()
{
std::矢量结果;
字符串文本=
“阿列克谢维奇、斯维特拉娜和林达尔、托马斯和坎贝尔、威廉”;
大小\u t pos=0;
对于(;;){
size\u t next=text.find(“and”,pos);
结果:向后推(text.substr(pos,next-pos));
如果(next==std::string::npos)中断;
pos=next+3;
}
用于(自动结果:结果)
{
std::cout
包含此任务的右搜索工具
vector<string> results;
const string text{ "Alexievich, Svetlana and Lindahl,Tomas and Campbell,William" };
const string delim{ " and " };
for (auto p = cbegin(text); p != cend(text); ) {
const auto n = search(p, cend(text), cbegin(delim), cend(delim));
results.emplace_back(p, n);
p = n;
if (cend(text) != n) // we found delim, skip over it.
p += delim.length();
}
矢量结果;
常量字符串文本{“Alexievich,Svetlana和Lindahl,Tomas和Campbell,William”};
常量字符串delim{“和”};
对于(自动p=cbegin(文本);p!=cend(文本);){
const auto n=搜索(p,cend(text),cbegin(delim),cend(delim));
结果:后侵位(p,n);
p=n;
如果(cend(text)!=n)//我们找到了delim,跳过它。
p+=极限长度();
}
这就是的意思,它匹配字符串中的任何字符。第三个参数是谓词,表示它可以是包括lambdas在内的任何可调用对象。另一个问题是它似乎是基于字符的,而不是“word”基于。@JoachimPileborg,感谢您的评论。替换为什么?如果扫描文本包含“Copeland,Amit”…您将在包含的“and”上“拆分”。如果find()失败,则调用substr(pos,npos pos)
@DavidThomas Re:contained“and”时出错。问题陈述中没有任何内容表明程序不应在此基础上拆分。引用OP:“我想通过出现和(强调我的)来拆分字符串。Re:substr
-不,我没有错误。事实上,程序应该调用substr(pos,npos-pos)
最终,它工作得很好。我被纠正了。我知道substr将接受NPO并返回字符串的其余部分,但从未见过比字符串长的任何值也能做同样的事情。嗯,谢谢你的教训。
vector<string> results;
const string text{ "Alexievich, Svetlana and Lindahl,Tomas and Campbell,William" };
const string delim{ " and " };
for (auto p = cbegin(text); p != cend(text); ) {
const auto n = search(p, cend(text), cbegin(delim), cend(delim));
results.emplace_back(p, n);
p = n;
if (cend(text) != n) // we found delim, skip over it.
p += delim.length();
}