从字符串中提取整数 [英] Extraction of integers from strings

查看:196
本文介绍了从字符串中提取整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从字符串中提取整数并将其保存到整数数组的最佳和最短方法是什么?

What is the best and shortest way to extract integers from a string and save them to an array of integers?

示例字符串"65 865 1 3 5 65 234 65 32#$!@#"

Sample string " 65 865 1 3 5 65 234 65 32 #$!@#"

我尝试查看其他一些帖子,但找不到有关此特定问题的帖子... 一些帮助和解释将非常有用.

I tried taking look at some other posts but couldn't find one about this specific issue... Some help and explanation would be great.

推荐答案

似乎可以全部通过std::stringstream完成:

It seems this can all be done with std::stringstream:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int main() {
    std::string str(" 65 865 1 3 5 65 234 65 32 #$!@#");
    std::stringstream ss(str);
    std::vector<int> numbers;

    for(int i = 0; ss >> i; ) {
        numbers.push_back(i);
        std::cout << i << " ";
    }
    return 0;
}


这是解决数字之间非数字的解决方案:


Here is a solution that accounts for non digits between numbers:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;

struct not_digit {
    bool operator()(const char c) {
        return c != ' ' && !std::isdigit(c);
    }
};

int main() {
    std::string str(" 65 865 1 3 5 65 234 65 32 #$!@# 123");
    not_digit not_a_digit;
    std::string::iterator end = std::remove_if(str.begin(), str.end(), not_a_digit);
    std::string all_numbers(str.begin(), end);
    std::stringstream ss(all_numbers);
    std::vector<int> numbers;

    for(int i = 0; ss >> i; ) {
        numbers.push_back(i);
        std::cout << i << " ";
    }
    return 0;
}

这篇关于从字符串中提取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆