C++ 如何将字符串的一部分转换为整数?

C++ 如何将字符串的一部分转换为整数?,c++,string,C++,String,我知道如何将完整字符串转换为整数(使用std::stoi)。但你能告诉我如何从字符串中提取整数吗。例如,我想从字符串a15a中提取整数15 string x="a15a"; int a = std::stoi(x); 如果整数位于字符串的开头,则上述方法可以正常工作。例如,如果字符串x的值是“15a”,它将其转换为15的整数。但是如果整数存在于字符串中间的某个地方,它就不起作用了。如何从字符串之间提取整数。 谢谢。另一种方法:您可以用空格替换非数字,以便直接使用stringstring提取剩余

我知道如何将完整字符串转换为整数(使用
std::stoi
)。但你能告诉我如何从字符串中提取整数吗。例如,我想从字符串
a15a
中提取整数
15

string x="a15a";
int a = std::stoi(x);
如果整数位于字符串的开头,则上述方法可以正常工作。例如,如果
字符串x
的值是
“15a”
,它将其转换为
15
的整数。但是如果整数存在于字符串中间的某个地方,它就不起作用了。如何从字符串之间提取整数。
谢谢。

另一种方法:您可以用空格替换非数字,以便直接使用
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";
使用C++17,您可以使用从字符序列中提取数值。您的代码看起来像:

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

请注意,我忽略了错误检查。阅读该链接,了解如何使用函数的返回值。

如果分隔十进制数的总是单个字符
a
,则任务将变为“按字符拆分字符串”。以下是我对以下内容的改编:

std::stringstream输入(“15a16a17”);
字符串部分;
std::向量数;
while(std::getline(输入,部分'a'))
{
数字。推回(标准::stoi(部分));
}

您可以使用
isdigit()
函数检查每个字符,以确定它是否为数字。然后,您可以组合顺序数字以提取整数。通过这种方式,您可以从任何字符串中提取数字,而不仅仅是由特定字符分隔的数字

更新:

正如@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]);

您可以非常简单地通过使用函数来定位字符串中第一个出现的数字。包含
使
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;
    }
示例使用/输出

$ /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;
}
#包括
#包括
#包括
#包括
int main()
{
使用名称空间std;
std::字符串主题(“a1b2c12d1212e”);
试一试{
std::regex re(“\\d+”);
std::sregx_迭代器next(subject.begin(),subject.end(),re);
std::sregx_迭代器端;
while(下一步!=结束){
std::smatch match=*下一步;

std::您是否可以首先使用提取数字部分,以便与
stoi
一起使用。您能否提供有关您输入的更多详细信息?它是否为固定格式(即字母,然后是数字,然后可能是其他字母)?您是否总是只有一个数字部分?(即不是“a15a21b”)?是的,我的输入是这样的固定格式:
“15a16a17”
。我想从中提取
15
16
17
。它有三个整数。@UsamaTahir是分隔符,总是
a
-并且总是一个字符?@UsamaTahir那么你不能让负数显示为正数吗?@TobySpeight是的,就像它不能容纳十进制va一样lues也是。但问题并不意味着这些都是考虑因素。我认为问题确实意味着数字可以是负数(虽然不是小数),通过对结果使用有符号的
int
。如果只有正值有用,那肯定是无符号类型?@TobySpeight它只对正数有效(和目前为止的其他答案一样)但是你也可以编辑代码来处理负数
    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;
    }
#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;
}