如何从字符串中获取数字

How to get a digit from a string?

本文关键字:获取 数字 字符串      更新时间:2023-10-16

例如,有一个包含"1234"的字符串n。

string n = "1234"

现在,有 int a、b、c、d 用于分别存储 1、2、3、4。

a is 1
b is 2
c is 3
d is 4

如何使用标准函数从字符串"12345"中获取这些数字?


以前,我使用以下方式。

int getDigit(string fourDigitString,int order)
{
    std::string myString = fourDigitString;
    int fourDigitInt = atoi( myString.c_str() ); // convert string fourDigitString to int fourDigitInt
    int result;
    int divisor = 4 - order;
    result = fourDigitInt / powerOfTen(divisor);
    result = result % 10;
    return result;
}

感谢您的关注

为了详细说明我的评论和ShaltielQuack的答案,以便您知道为什么只是从数字中减去字符'0',您可能需要查看ASCII表。

在那里,您将看到字符'0'的 ASCII 代码是十进制48 。如果您随后看到 ASCII 代码,例如 '1'又是一个,49.因此,如果您执行'1' - '0'则与执行49 - 48相同,这会导致十进制值1

std::string n ("12345");
int a, b, c, d, e;
a = str.at(0);
...
#include <iostream>
using namespace std;
int main() {
    string n = "12345";
    int a = n[0] - '0';
    int b = n[1] - '0';
    int c = n[2] - '0';
    int d = n[3] - '0';
    int e = n[4] - '0';
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cout << d << endl;
    cout << e << endl;
}

输出:

1阿拉伯数字

3

5

您可以尝试以下代码:

#include <string>
#include <sstream>
int main() {
    std::string s = "100 123 42";
    std::istringstream is( s );
    int n;
    while( is >> n ) {
         // do something with n
    }
}

这个问题:从字符串中拆分 int