c++将字符串拆分为另一个字符串作为整体
C++ split string by another string as whole
我想按出现and
的任意次数分割字符串。
首先,我必须说清楚,我不打算使用任何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;
}
,结果与我期望的不同:
Alexievich,
Svetl
Li
hl,Tom
s
C
mpbell,Willi
m
分隔符中的每个字符似乎都单独起作用,而我需要将整个and
作为分隔符。
请不要链接到这个boost示例,除非你确定它将适用于我的情况
<algorithm>
包含此任务的搜索权限工具。
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();
}
老办法:
#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;
}
打包成一个可重用的函数留给读者作为练习。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 使用另一个字符串从字符串中删除空格
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何在使用 getch 后在另一个字符串的末尾连接一个字符串
- 如何在另一个字符串的x位置插入一个字符串?
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- C++:递归地将字符串中一个字母的所有实例替换为另一个字母
- 在另一个字符串中插入文件扩展名之前的字符串
- 使用C++将一个字符串替换为另一个字符串
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将字符串中的单个单词替换为另一个单词
- 将文本流中一个字符串的所有匹配项替换为另一个字符串
- 无法将字符串用作另一个类的参数
- 另一个字符串文字,UDL 迷宫
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 如何使用循环从另一个字符串创建一个没有空格的新字符串