从字符串中提取整数

3
什么是从字符串中提取整数并将其保存到整数数组中的最佳且最短的方法?
示例字符串“ 65 865 1 3 5 65 234 65 32 #$!@#”
我尝试查看其他帖子,但没有找到关于这个特定问题的帖子... 需要一些帮助和解释。

你的字符串是否总是以非数字字符#开头,并放在字符串的末尾? - taocp
我的字符串实际上全部是整数,但以一个非数字字符结尾,例如:"1 4 5 2 54 65 3246 53490 80 9 #"。 - Ezz
你可以试着看看stringstream吗?或者看看这个来自topcoder的教程?我想这样你可以学到更多:http://community.topcoder.com/tc?module=Static&d1=features&d2=112106 这篇文章也许会有用:https://dev59.com/k3VC5IYBdhLWcg3wnCj6 - taocp
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;
}

似乎在这种情况下仅使用 stringstream 是行不通的:" 65 865 1 3 5 65 234 65 32 #$!@# 123" - andre
啊,现在我看到了。我会将这个解决方案添加到底部,以防有人需要它。 - andre

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++);
}

所以你可以看到,我已经将它缩减为一组字符串。如果您需要将其转换为整数数组(不确定您想要哪种数组类型),请告诉我整个步骤;如果您想采用boost方式,我也很乐意包含这部分。


这个代码能够满足OP的需求吗?示例字符串“65 865 1 3 5 65 234 65 32 #$!@#” - Haseeb Mir

0

您可以使用stringstream来保存字符串数据,然后使用典型的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() 

检查将字符串读入整数是否成功。


0

我喜欢使用istringstream来做这件事

istringstream iss(line);
iss >> id;

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接