簡體   English   中英

如何從字符串中提取整數?

[英]How can I extract integers from a string?

考慮一個形式的字符串

“列數 = 5
行數 = 345
1 3 -5 2 9
4 -10 34 -22 7"

[后面還有 343 行。 不過,我想這足以解釋問題了。]

我希望將值5345提取為整數。 子字符串“列數=”和“行數=”是已知的,但這些字符串后面的值中的位數是未知的。 但是,已知相應的行在值之后結束。 我可以使用以下代碼到達數字的開頭

std::string searchString = "clause length = ";
int searchStringLength = searchString.length();
std::size_t startAt = result.find(searchString) + searchStringLength;

但是,我不知道如何檢測行尾,使用它可以提取值。

下一部分是提取其余的整數並將它們存儲在一個數組中,我想如果我能識別空格和行尾的位置,這個問題也將得到解決。

如何有效地解決這個問題[我使用的是 Visual Studio 2017]?

嘗試以下基於正則表達式的簡單數字提取器

#include <iostream>
#include <iterator>
#include <string>
#include <regex>

int main()
{
    std::string s = "number of columns = 5\n"
        "number of rows = 345\n"
        "1 3 -5 2 9\n"
        "4 -10 34 -22 7\n";

    std::regex num_regex("\\d+|-\\d+");
    auto num_begin = 
        std::sregex_iterator(s.begin(), s.end(), num_regex);
    auto num_end = std::sregex_iterator();

    for (std::sregex_iterator i = num_begin; i != num_end; ++i) {
        std::smatch match = *i;
        std::string match_str = match.str();
        std::cout << "  " << match_str << '\n';
    }

}

輸出

  5
  345
  1
  3
  -5
  2
  9
  4
  -10
  34
  -22
  7

您可以將字符串拆分為標記。 在這種情況下,根據“=”符號拆分字符串,然后嘗試將它們轉換為整數的http://www.cplusplus.com/reference/cstring/strtok/通過此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM