簡體   English   中英

如何將部分字符串轉換為 integer?

[英]How to convert a part of string into integer?

我知道如何將完整的字符串轉換為整數(使用std::stoi )。 但是你能指導我如何從字符串中提取 integer 嗎? 例如,我想從字符串a15a中提取 integer 15

string x="a15a";
int a = std::stoi(x);

如果 integer 位於字符串的開頭,則上述方法可以正常工作。 例如,如果string x的值為"15a" ,則將其轉換為 integer 15 但如果 integer 出現在字符串中間的某個位置,則它不起作用。 如何從字符串之間提取 integer。 謝謝。

使用 C++17 您可以使用std::from_chars從字符序列中提取數值。 你的代碼看起來像:

std::string x = "a15a";
int a = 0; // initialize with some value in case parsing fails
std::from_chars(&x[1], &x[3], a); // parse from [first, last) range of chars

請注意,我省略了錯誤檢查。 閱讀該鏈接以了解如何使用 function 的返回值。

另一種方式:您可以用空格替換非數字,以便直接使用剩余整數的stringstring提取:

std::string x = "15a16a17";
for (char &c : x)
{
    if (!isdigit(c))
        c = ' ';
}

int v;
std::stringstream ss(x);
while (ss >> v)
    std::cout << v << "\n";

Output:

15
16
17

您可以使用isdigit() function 檢查每個字符以確定它是否為數字。 然后您可以結合連續數字來提取 integer。 這樣,您可以從任何字符串中提取數字,而不僅僅是用特定字符分隔。

更新:

正如@Toby 所提到的,我也更新了代碼以處理負數。

string input="14aaa15d-16fff-fff17";
string tmp = "";
vector<int> output;
for (int i = 0; i < input.size(); ++i)
{
    if (isdigit(input[i]))
    {
        if(i>0 && input[i-1]=='-')
            tmp+='-';
        tmp+=input[i];
    }
    else if(tmp.size()>0)
    {
        output.push_back(stoi(tmp));
        tmp = "";
    }
}

if (tmp.size()>0)
    output.push_back(stoi(tmp));

for (int i = 0; i < output.size(); ++i)
    printf("%d ", output[i]);

Output:

14
15
-16
17

如果總是用單個字符a分隔十進制數,則任務變為“按字符拆分字符串”。 這是我對同名 SO 問題的接受答案的改編:

std::stringstream input("15a16a17");
std::string part;
std::vector<int> numbers;

while(std::getline(input, part, 'a'))
{
   numbers.push_back(std::stoi(part));
}

您可以非常簡單地使用 function 來定位字符串中第一次出現的數字。 包含<cstring>使strspn()可用並使該過程變得微不足道。

例如,要查找"a15a"中的第一個數字字符,您只需撥打電話:

    int a;
    size_t off, pos;
    std::string x = "a15a";

    off = strcspn (x.c_str(), "0123456789");    /* get no. chars to 1st digit */

off現在保存到x中第一個數字的偏移量。 此時的轉換很簡單,但是要驗證轉換,您必須使用try {...} catch (exception) {...}格式,否則您將不知道嘗試轉換后的值a是否有效,例如

    try {   /* validate using try {..} catch (exception) {..} */
        a = std::stoi(x.c_str() + off, &pos);   /* good conversions, store a */
        std::cout << a << '\n';                 /* output number in "a15a" */
    }
    catch (const std::exception & e) {
        std::cerr << e.what() << '\n';
        return 1;
    }

這就是定位x中數字的開頭並驗證x + off處的轉換以達到所需的 integer 值所需的全部內容。

總而言之,您將擁有:

#include <iostream>
#include <string>
#include <cstring>

int main() {

    int a;
    size_t off, pos;
    std::string x = "a15a";

    off = strcspn (x.c_str(), "0123456789");    /* get no. chars to 1st digit */
    try {   /* validate using try {..} catch (exception) {..} */
        a = std::stoi(x.c_str() + off, &pos);   /* good conversions, store a */
        std::cout << a << '\n';                 /* output number in "a15a" */
    }
    catch (const std::exception & e) {
        std::cerr << e.what() << '\n';
        return 1;
    }
}

示例使用/輸出

$ /bin/stoi_int
15

正則表達式方式:

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

int main()
{
 using namespace std;

std::string subject("a1b2c12d1212e");
try {
  std::regex re("\\d+");
  std::sregex_iterator next(subject.begin(), subject.end(), re);
  std::sregex_iterator end;
  while (next != end) {
    std::smatch match = *next;
    std::cout << "number " << match.str() << "\n";
    next++;
  } 
} catch (std::regex_error& e) {
  // Syntax error in the regular expression
}

 return EXIT_SUCCESS;
}

暫無
暫無

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

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