如何从字符串中提取特定元素?

时间:2017-03-03 10:02:08

标签: c++ string

我正在尝试从下一个字符串中提取每个数字块的第一个数字。

string s = "f 1079//2059 1165//2417 1164//2414 1068//1980";

在这个例子中,我需要提取1079,1165,1164和1068

我尝试过使用getline和substr,但我无法做到。

4 个答案:

答案 0 :(得分:2)

您可以使用模式MethodNotAllowedHttpException的{​​{3}}(C ++正则表达式库)。在双斜线之前找到数字。也使用括号仅通过子匹配提取数字。

这是用法。

(\\d+)//

答案 1 :(得分:1)

我通常会为istringstream找到这种事情:

std::string input = "f 1079//2059 1165//2417 1164//2414 1068//1980";
std::istringstream is(input);
char f;
if (is >> f)
{
    int number, othernumber;
    char slash1, slash2;
    while (is >> number >> slash1 >> slash2 >> othernumber)
    {
        // Process 'number'...
    }
}

答案 2 :(得分:0)

这是尝试使用getline和substring。

auto extractValues(const std::string& source)
-> std::vector<std::string>
{
    auto target = std::vector<std::string>{};
    auto stream = std::stringstream{ source };
    auto currentPartOfSource = std::string{};
    while (std::getline(stream, currentPartOfSource, ' '))
    {
        auto partBeforeTheSlashes = std::string{};
        auto positionOfSlashes = currentPartOfSource.find("//");
        if (positionOfSlashes != std::string::npos)
        {
            target.push_back(currentPartOfSource.substr(0, positionOfSlashes));
        }
    }
    return target;
}

答案 3 :(得分:0)

或者有另一种分割方式来提取令牌,但它可能涉及一些字符串复制。

考虑split_by函数,如

std::vector<std::string> split_by(const std::string& str, const std::string& delem);

Split a string in C++?

中可能的实施方式

首先按分割字符串,然后按//分割并提取第一项。

std::vector<std::string> tokens = split_by(s, " ");
std::vector<std::string> words;
std::transform(tokens.begin() + 1, tokens.end(),  // drop first "f"              
               std::back_inserter(words), 
               [](const std::string& s){ return split_by(s, "//")[0]; });