从字符串中提取整数
Extraction of integers from strings
从字符串中提取整数并将其保存到整数数组的最佳和最短方法是什么?
示例字符串" 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
。
相关文章:
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 从没有空格的字符串中提取整数
- 如何从字符数组C++中提取2个整数并将它们存储在2个变量中(初学者)
- 如何将ASCII数字转换为从文件中提取的整数
- 如何从字符串格式中提取 3 个整数"v%d.%d.%d"?
- C++从字符串中提取整数
- 从QString中提取整数
- 如何提取字符串中的整数?
- 从字符串中提取整数
- Systemc传输级建模从TLM_Generic_Payload提取两个整数
- 使用C 从定界线拆分字符串中提取整数数组
- 从用户输入中提取整数的枚举开关语句
- C++ 提取具有多个分隔符的字符串中的整数
- 如何从整数中提取缺失的数字
- 如何从两个字符之间的文件中提取整数
- C++ - 从整数数组中插入和提取字符
- 从字符串中提取整数
- C++,从字符数组中提取有符号的多位数整数
- 使用增强精神提取未阐明的字符串和整数