2017-03-03 77 views
0

我想从下一个字符串的每个数字块中提取第一个数字。如何从字符串中提取特定元素?

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

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

我试图与函数getline和SUBSTR,但我一直没能来。

+1

告诉我们你试过了什么(特别是substr尝试)。同时向我们描述您的解决方案如何工作。我们可能会帮助您解决问题。 – user2079303

+0

使用间距作为分隔符在子字符串中剪切行,然后从每个这些子字符串中提取第一个数字。 –

回答

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'... 
    } 
} 
0

这里是函数getline和其子工作的尝试。

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; 
} 
2

可以利用<regex>(C++正则表达式库)与图案(\\d+)//。找到双斜杠前的数字。同样使用括号仅通过submatch提取数字。

这里是用法。

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

std::regex pattern("(\\d+)//"); 
auto match_iter = std::sregex_iterator(s.begin(), s.end(), pattern); 
auto match_end = std::sregex_iterator(); 

for (;match_iter != match_end; match_iter++) 
{ 
    const std::smatch& m = *match_iter; 
    std::cout << m[1].str() << std::endl; // sub-match for token in parentheses, the 1079, 1165, ... 
              // m[0]: whole match, "1079//" 
              // m[1]: first submatch, "1070" 
} 
0

或者还有另一种拆分方式来提取令牌,但它可能涉及一些字符串副本。

考虑Split a string in C++?

制作绳一split_by功能像

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

可能实现由第一,然后通过//分裂和提取第一项劈裂。

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]; });