从字符串中提取整数

Extraction of integers from strings

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

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

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

我试着看看其他一些帖子,但找不到关于这个特定问题的帖子…

似乎这一切都可以用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;
}

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

#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;
}

由于这里分隔符的复杂性(您似乎有空格和非数字字符),我将使用boost库中可用的字符串分割:

http://www.boost.org/

这允许您使用正则表达式作为分隔符进行分割。

首先,选择一个正则表达式作为分隔符:

boost::regex delim(" "); // I have just a space here, but you could include other things as delimiters.

然后提取如下:

std::string in(" 65 865 1 3 5 65 234 65 32 ");
std::list<std::string> out;
boost::sregex_token_iterator it(in.begin(), in.end(), delim, -1);
while (it != end){
    out.push_back(*it++);
}

你可以看到我把它简化成了字符串列表。让我知道,如果你需要做整个步骤的整数数组(不确定你想要什么数组类型);

您可以使用stringstream来保存字符串数据并将其读出

#include <iostream>
#include <sstream>
int main(int argc, char** argv) {
   std::stringstream nums;
   nums << " 65 865 1 3 5 65 234 65 32 #$!@#";
   int x;
   nums >> x;
   std::cout <<" X is " << x << std::endl;
} // => X is 65

这将吐出第一个数字,65。清理数据则是另一回事。你可以检查

nums.good() 

查看读入int类型是否成功。

我喜欢使用istringstream

istringstream iss(line);
iss >> id;

因为它是一个流,你可以像cin一样使用它。默认情况下,它使用空格作为分隔符。您可以简单地将其封装在一个循环中,然后将得到的string转换为int

http://www.cplusplus.com/reference/sstream/istringstream/istringstream/