I am work开发者_运维问答ing 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?
You may take a look at std::istringstream and its >> operator (not as explicit as sscanf though).
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.
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 the
double iterator constructors of std::string
, will give you the
strings, e.g.:
std::string::const_iterator posT = std::find( s.begin(), s.end(), 'T' );
std::string::const_iterator posSpace = std::find( posT, s.end(), ' ' );
std::string date( s.begin(), posT );
std::string time( posT != posSpace ? posT + 1 : posT , posSpace );
(You'll probably want better error handling that I've provided.)
you can use strsep()
or strtok_r()
to split this string in what you want with your separators (in your case 'T' and ':').
精彩评论