0

Let assume we have such URL:

dvb://1.3f3.255c.15

my question is how to parse this address in following way:

val1 = 1
val2 = 3f3
val3 = 255c
val4 = 15

First idea is to use strchr() from standard C library, but maybe done it before. I would like to make it as simple as possible. When I will succeed I will put my solution.

Best Regards

Alexander
  • 23,432
  • 11
  • 63
  • 73
bartebly
  • 29
  • 1
  • 4

3 Answers3

2

You could use strtok

char dvb_url[] = "dvb://1.3f3.255c.15";

//Begin stripping the scheme (dvb:/)
char *tokenized = strtok(dvb_url, "/");
//Finish stripping scheme
tokenized = strtok(NULL, "/.");

while(tokenized != NULL)
{
    //Store in variable here            
    printf("%s\n", tokenized);
    tokenized = strtok(NULL, ".");
}
Joe
  • 56,979
  • 9
  • 128
  • 135
  • Be aware that strtok will modify the original string replacing the tokenized characters with `\0`. If you would like to maintain the orignal string consider a `memcpy` or `memmove`. (note: If the scheme is missing (dvb://) it would fail) – Joe Aug 19 '11 at 15:13
1

There is a very simple answer if your pattern is fixed. I don't how many people use it like this.

sscanf() is very handy here :)

char *dvb_string = "dvb://1.3f3.255c.15";
char proto[10], output1[10], output2[10], output3[10], output4[10];
sscanf(dvb_string, "%[^:]://%[^.].%[^.].%[^.].%s", proto, output1, output2, output3, output4);
fprintf(stderr, "%s -- > %s %s %s %s %s\n", dvb_string, proto, output1, output2, output3, output4);

OUTPUT:

dvb://1.3f3.255c.15 -- > dvb 1 3f3 255c 15

Simple as this :) enjoy C.

Regards

Alexander
  • 23,432
  • 11
  • 63
  • 73
0

I think the strchr() function is handy enough:

char *str = "dvb://1.3f3.255c.15";
char val[10][256];
char *cur = str;
int i = 0;

for ( ; cur = strchr(str, '.'); cur != NULL && i < 10)
{
    strncpy(val[i], cur, 256);
    if(strchr(val[i], '.') != NULL)
        strchr(val[i], '.') = '\0';
    ++i;
}

You should end up with your values in val[0 to N].

Constantinius
  • 34,183
  • 8
  • 77
  • 85