如何在没有 boost 的情况下标记字符串?
我正在 C++ 工作。我有以下字符串:
2011-07-01T14:32:39.1846579+02:00
有人能告诉我如何在另一个字符串中提取 2011-07-01 14:32 吗?
I am working in C++. I have the following string:
2011-07-01T14:32:39.1846579+02:00
Can someone tell me how can I extract 2011-07-01 14:32 in another string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以看一下 std::istringstream 及其 >>运算符(虽然不如 sscanf 那么明确)。
You may take a look at std::istringstream and its >> operator (not as explicit as sscanf though).
我认为 sscanf 就是您正在寻找的:
http://www.cplusplus.com /reference/clibrary/cstdio/sscanf/
然后,您可以使用
snprintf
重新格式化数据。I think that sscanf is what you are looking for :
http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
You can then use
snprintf
to reformat the data.如果您有 C++11,最简单的解决方案是使用常规
表达式。也可以使用
std::istringstream
,特别是如果你有一些额外的操纵器,例如匹配
单个字符。 (如果你不这样做,你可能应该这样做。问题
经常发生。)然而,对于这么简单的事情,这两种情况
解决方案可能被认为是过度杀伤:
std::find
for'T'
,然后 for' '
将为您提供两个字符中每一个的迭代器,并且std::string
的双迭代器构造函数将为您提供字符串,例如:(
您可能需要我提供的更好的错误处理。)
If you have C++11, the simplest solution would be to use regular
expresssions. It's also possible to use
std::istringstream
,especially if you have some additional manipulators for e.g. matching a
single character. (If you don't, you probably should. The problem
occurs often enough.) For something this simple, however, both of these
solutions might be considered overkill:
std::find
for'T'
, then for' '
will give you an iterator for each of the two characters, and thedouble iterator constructors of
std::string
, will give you thestrings, e.g.:
(You'll probably want better error handling that I've provided.)
您可以使用
strsep()
或strtok_r()
将此字符串按照您想要的分隔符(在您的情况下为“T”和“:”)分割。you can use
strsep()
orstrtok_r()
to split this string in what you want with your separators (in your case 'T' and ':').