2

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

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

我尝试查看其他一些帖子,但找不到有关此特定问题的帖子...一些帮助和解释会很棒。

4

4 回答 4

4

似乎这一切都可以通过以下方式完成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;
}
于 2013-06-07T15:27:41.667 回答
1

由于此处分隔符的复杂性(您似乎有空格和非数字字符),我将使用 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++);
}

所以你可以看到我已经把它简化为一个字符串列表。让我知道您是否需要对整数数组执行整个步骤(不确定您想要什么数组类型);如果您想采用增强方式,也很高兴将其包括在内。

于 2013-06-07T15:21:46.747 回答
0

您可以使用字符串流来保存字符串数据,并使用典型的 C++ iostream 机制将其读取为整数:

#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 是否成功。

于 2013-06-07T15:24:24.053 回答
0

我喜欢用istringstream这个

istringstream iss(line);
iss >> id;

由于它是一个流,您可以像使用它一样使用它cin。默认情况下,它使用空格作为分隔符。您可以简单地将其包装在一个循环中,然后将结果转换stringint.

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

于 2013-06-07T15:25:44.040 回答