0

I am trying to split my actual key on dot and then extract all the fields from after splitting it on dot.

My key would look like something this -

@event.1384393612958.1136580077.TESTING

Currently, I am able to extract only the first field which is @event after splitting it on the dot. Now how to extract all the other fields as well. Below is my code, I am using currently to extract the first field from it.

if (key)
{
    char* first_dot = strchr(key, '.');
    if (first_dot)
    {
        // cut at the first '.' character
        first_dot[0] = 0;
    }
}

cout << "Fist Key: " << key << endl;

And then after extracting individual fields, store the second field as uint64_t, third field as uint32_t and last field as string.

Update:-

This is what I have got now -

if (key)
{
char *first_dot = strtok(key, ".");
char *next_dot = strtok(NULL, ".");

uint64_t secondField = strtoul(next_dot, 0, 10);

cout << first_dot << endl;
cout << secondField << endl;

}

From which I am able to extract first and second field. What about third and fourth field?

AKIWEB
  • 19,008
  • 67
  • 180
  • 294

1 Answers1

1

You can use strtok instead. strtok does exactly, what you're doing right now. It splits the string, when it encounters a delimiting character

if (key) {
    char *first_dot = strtok(key, ".");
    ...
    char *next_dot = strtok(NULL, ".");
}

The conversion to some int type can be done with strtoul/strtoull

uint64_t i = strtoul(next_dot, 0, 10);
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • thanks for example. Now I am wondering how to extract individual fields form it? Pardon my ignorance in C++.. I recently started working with it. Thanks for the help. – AKIWEB Nov 14 '13 at 20:33
  • What do you mean with extracting fields? With `first_dot` or `next_dot`, you already have access to the first and second field. – Olaf Dietsche Nov 14 '13 at 20:36
  • I see.. now it makes sense and now I am able to extract first and second field.. I updated my question with the code that I am using now.. Similarly I need to extract third and fourth fields as well? – AKIWEB Nov 14 '13 at 20:46
  • This is explained at the link/manual to strtok. In the first call, you give the string to parse. In all following calls, you pass NULL as the first argument, until strtok returns NULL (no more tokens). – Olaf Dietsche Nov 14 '13 at 20:52
  • And also, it's a silly question, but thought to ask you - should I be splitting the string like the way I am doing currently or should I use the method described [here](http://stackoverflow.com/a/5167799/819916) by using `istringstream` ? – AKIWEB Nov 14 '13 at 20:57
  • This (my) answer is more C-like. This means it works with C-strings, when you use `char*`. When you have C++ `std::string`s instead, it's better to use a C++ method like the one in the other answer. – Olaf Dietsche Nov 14 '13 at 21:03