什么是从字符串中提取整数并将其保存到整数数组中的最佳且最短的方法?
示例字符串“ 65 865 1 3 5 65 234 65 32 #$!@#”
我尝试查看其他帖子,但没有找到关于这个特定问题的帖子... 需要一些帮助和解释。
示例字符串“ 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;
}
stringstream
是行不通的:" 65 865 1 3 5 65 234 65 32 #$!@# 123"
。 - andre由于这里的分隔符较为复杂(似乎包含空格和非数字字符),我建议使用boost库中提供的字符串分割功能:
这使您能够使用正则表达式作为分隔符进行分割。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方式,我也很乐意包含这部分。
您可以使用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()
检查将字符串读入整数是否成功。
我喜欢使用istringstream
来做这件事
istringstream iss(line);
iss >> id;
由于它是一个流,你可以像使用 cin
一样使用它。默认情况下,它使用空格作为分隔符。你可以简单地将其包装在循环中,然后将结果的 string
强制转换为 int
。
http://www.cplusplus.com/reference/sstream/istringstream/istringstream/
#
开头,并放在字符串的末尾? - taocp