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