如何用“|”分隔字符串作为分隔符?如何将它存储在两个变量中

How to separate a string with "|" as the separator? How to store it in two variable

我有一个字符串。

Input:

std::string kind = 0123|0f12;

我们有分隔符“|”。

我想将这两个值存储到两个变量中。我该怎么做?

Output:
    std::string kind1 = 0123;

    std::string kind2 = 0f12;

使用std::string的成员函数find, substr and erase。试试这个:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::string s = "0123|0f12";
    std::string delimiter = "|";

    size_t pos = 0;
    std::vector<std::string> vec;
    while ((pos = s.find(delimiter)) != std::string::npos) {
        std::string token = s.substr(0, pos);
        vec.push_back(token);
        s.erase(0, pos + delimiter.length());
    }
    if (!s.empty())
        vec.push_back(s);
    for (const auto& i: vec)
        std::cout << i << std::endl;
    return 0;
}

输出:

0123
0f12
std::string kind = "0123|0f12";
std::size_t found = kind.find("|");
if (found != std::string::npos)
{
   std::string kind1 = kind.substr(0,found-1);
   std::string kind2 = kind.substr(found+1);
}