0

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?

Bo Persson
  • 88,437
  • 31
  • 141
  • 199
sunset
  • 1,281
  • 3
  • 21
  • 33
  • possible duplicate of [How do I tokenize a string in C++?](http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c) – iammilind Aug 01 '11 at 07:45
  • Are you asking how to deal with that special string, or wounder how tokenizing works generally? – nicks Aug 01 '11 at 07:47

4 Answers4

4

You may take a look at std::istringstream and its >> operator (not as explicit as sscanf though).

Jonathan Merlet
  • 275
  • 3
  • 13
2

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.

Nicol Bolas
  • 413,367
  • 61
  • 711
  • 904
Clement Bellot
  • 823
  • 1
  • 7
  • 19
  • 2
    `sscanf(...)` is part of "simple" C. In general choosing a STL/C++ solution is usually the safer way to go. Which can mean - for example - that you get errors at compile time rather than runtime. And often the STL/C++ solution is also easier to read. I strongly suggest you have a look at the ">>"-operator, the -class, and the -class. – AudioDroid Aug 01 '11 at 09:45
  • Downvoted, mostly because it got accepted. It's a possible solution, but not "the C++ way". C++11 regex or `std::istringstream` are definitely better solutions. – Lstor Aug 01 '11 at 10:23
2

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.)

James Kanze
  • 146,674
  • 16
  • 175
  • 326
0

you can use strsep() or strtok_r() to split this string in what you want with your separators (in your case 'T' and ':').

hari
  • 9,203
  • 26
  • 71
  • 110