C++将包含单词和数字的字符串转换为数字

C++ convert string with word and number to number

本文关键字:数字 字符串 转换 包含单 C++      更新时间:2023-10-16

如何将类似3 word 12 with word的字符串转换为只包含数字312的int,而不在C++中使用stoi?当我尝试使用Codeblode时,它给了我一个错误stoi is not a member of std

提前谢谢!

遍历该行并跳过非数字符号。对于数字,采用-'0'转换和*10移位方法。例如:

#include <stdio.h>
#include <ctype.h>
//or cctype to use isdigit()
#include <string.h>
//or cstring to use strlen()
int main()
{
    char str[] = "3 word 12 with word"; // can be any string
    int result = 0; // to store resulting number
    // begin of solution
    for (int i = 0; i < strlen(str); i++)
    {
        if (isdigit(str[i]))
        {
            result *= 10;
            result += str[i] - int('0');
        }
    }
    // end of solution
    printf("%dn", result);
    return 0;
}

与VolAnd的答案中的想法相同。只是,因为这个问题被标记为c++,使用了一些STL的东西。

#include <iostream>
#include <numeric>
#include <string>
using namespace std;
int main(){
    std::string input("3 word 12 with word");
    int num = std::accumulate(input.begin(), input.end(), 0,
            [](int val, const char elem) {
                if (isdigit(elem)) {
                    val = val*10 + (elem-'0');
                }
                return val;
        }
    );
    std::cout << num << std::endl;
    return 0;
}

参见http://en.cppreference.com/w/cpp/algorithm/accumulate

注意:如果你想允许一个前导减号,它会变得稍微有趣一些…

使用boost::adaptors::filter(rng,pred)会很有趣,但有点过头了;-)

假设s是您的初始字符串。

int toInt(string s) {
    string digits;
    for(size_t i = 0; i < s.size(); i++)
        if(s[i] >= '0' && s[i] <= '9')
            digits.push_back(s[i]);
    int res = 0;
    for(size_t i = 0; i < digits.size(); i++)
        res = res * 10 + digits[i] - '0';
    return res;
}

前导零不是问题。但是,请注意,如果生成的digits字符串将包含一个大数字,则可能会接收到溢出。