c++ - 在C ++中连接两个字符串中用逗号分隔的唯一值
问题描述
CString s;
int res = 0;
char *existing;
char *current;
existing = strtok(urls, ",");
current = strtok(storedurls, ",");
while (existing != NULL)
{
while (current != NULL)
{
res = strcmp(existing, current);
if (res == 0) continue;
s.Append(current);
current = strtok(NULL, ",");
if (current != NULL) s.Append(",");
}
existing = strtok(NULL, ",");
}
strcat(urls, s);
我们有一个存储url L("url1,url2,url3") 和urls L("url3,url5") 的字符串,我想存储两个字符串中的唯一url 并获得一个输出为L("url1,url2, url3,url5")
解决方案
停止在 C++ 中使用 C 风格的字符串函数,并熟悉 C++ 标准库。
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
std::vector<std::string> split(std::string const& src, char delim = ',')
{
std::vector<std::string> dst;
std::stringstream ss{ src };
std::string tmp;
while (std::getline(ss, tmp, delim))
dst.push_back(tmp);
return dst;
}
int main()
{
std::string foo{ "url1,url2,url4" };
std::string bar{ "url2,url3,url5" };
auto foo_urls{ split(foo) };
auto bar_urls{ split(bar) };
std::vector<std::string> unique_urls{ foo_urls.begin(), foo_urls.end() };
unique_urls.reserve(foo_urls.size() + bar_urls.size());
unique_urls.insert(unique_urls.end(), bar_urls.begin(), bar_urls.end());
std::sort(unique_urls.begin(), unique_urls.end());
unique_urls.erase(std::unique(unique_urls.begin(), unique_urls.end()), unique_urls.end());
for (auto const& url : unique_urls)
std::cout << url << '\n';
}
推荐阅读
- json - handlebars-js - 更复杂的 json api
- camera - angular 6 PWA 自动化文件输入点击
- typescript - 切换到 ES2015 并使用 ts-node 时的模块地狱
- flask - 使用 Apache2 在网站的非根 url 上的烧瓶应用程序
- aframe - 鼠标单击 a-scene 时获取 xyz 位置
- java - 将 NMTOKENS 解组为列表
- python - 模拟函数根据传递的参数返回不同的值
- google-chrome - 访问问题中的 FollowHyperlink
- loops - 如何仅指定某些整数而不是循环遍历 lua 中的整个范围?
- ios - 从旧的 Dropbox SDK 迁移