从字符串中提取整数并将其保存到整数数组中的最佳和最短的方法是什么?
示例字符串“ 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)