C++ : Pick portions/data from a string having fixed format

标签 c++ string stl

我有一个固定格式的字符串。比方说:

This is 24 day of Aug of 2016

那么,在 C++ 中是否有一种简单的方法(类似于 C 中的 strtol),以便我可以将数据提取到变量中,如下所示:

day = 24;
month = "Aug";
year = 2016;

最佳答案

您可以使用 std::stringstream 来完成此操作.您可以将字符串加载到 stringstream 中,然后将其读入所需的变量中。它将为您转换为您正在使用的数据类型。例如你可以使用

std::string input = "This is 24 day of Aug of 2016";
std::stringstream ss(input)
std::string eater; // used to eat non needed input
std::string month;
int day, year;
ss >> eater >> eater >> day >> eater >> eater >> month >> eater >> year;

它看起来有点冗长,但现在您不需要使用 findsubstr 以及转换函数。

关于C++ : Pick portions/data from a string having fixed format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37483564/

相关文章:

c++ - 跨模板实例共享函数

Python 连接列表

c++ - make_heap() 函数如何工作?

c++ - 如何获得可调用类型的签名?

c++ - 如何将C++字符串放入char数组

c++ - 在子类中重用工厂类型构造函数

python - 如何判断数组中的任何元素是否是给定字符串的子字符串?

c++ - Visual C++ 2010 映射/设置迭代器不兼容

php - 强制类型 SWIG

java - 如何在其他单词的字符串中将逗号插入到数字中