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

问题描述 投票:-1回答:2

我有一个字符串。

Input:

std::string kind = 0123|0f12;

我们有分隔符“ |”。

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

Output:
    std::string kind1 = 0123;

    std::string kind2 = 0f12;
c++ variables stdstring separator
2个回答
1
投票
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);
}

1
投票

使用findsubstrerasestd::string成员函数。试试这个:

#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
© www.soinside.com 2019 - 2024. All rights reserved.