首页 > 解决方案 > 在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 风格的字符串函数,并熟悉 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';
}

推荐阅读