user1767288
user1767288

Reputation: 105

Breaking the string into parts in C

Its been long since I wrote a program in C language I have a string like the one below

"VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, plan 1, assa=784617896.9649164, plan24, massmedua=plan12, masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan"

and I need to get the ones before "=" i.e VRUWFB02, VRUWFB01, assa, massmedua, masspedia.

I am able to break the string but am not able to extract those specific words.

Can any one help me with this

char st[] = "VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, plan 1,assa=784617896.9649164, plan24, massmedua=plan12, masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan";
char *ch;
regex_t compiled;
char pattern[80] = "  ";
printf("Split \"%s\"\n", st);
ch = strtok(st, " ");
while (ch != NULL) {
    if(regcomp(&compiled, pattern, REG_NOSUB) == 0) {
        printf("%s\n", ch);
    }
    ch = strtok(NULL, " ,");
}
return 0;

Upvotes: 0

Views: 588

Answers (2)

Carl Norum
Carl Norum

Reputation: 224864

Here's a quick example program I made up to explain things:

#include <string.h>
#include <stdio.h>

int main(void)
{
    char s[] = "VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, "
               "plan 1, assa=784617896.9649164, plan24, massmedua=plan12, "
               "masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan";
    char *p;
    char *q;

    p = strtok(s, " ");
    while (p)
    {
        q = strchr(p, '=');
        if (q)
            printf("%.*s\n", (int)(q - p), p);
        p = strtok(NULL, " ");
    }

    return 0;
}

And output:

$ ./example
VRUWFB02
VRUWFB01
assa
massmedua
masspedia

The basic idea is to split the string by spaces, then look for = characters in the chunks. If one shows up, print the desired part of that chunk.

Upvotes: 2

Ivan Mushketyk
Ivan Mushketyk

Reputation: 8285

You can use strtok function to break a string. You can find an example of using it on the web page I gave reference to.

Upvotes: 0

Related Questions