-
please advise....
Hello,
Please advise on the best way to extract values of a string so that I can use them to insert into a db - I am thinking of doing it the following way (untested):
String is as follows (but will always contain a different amout of detail recs:
Code:
~STATUS*1~RECS*4~ACCESS*1256~NAME*Joe~SNAME*Bloggs~AGE*30~NAME*Joe~SNAME*Bloggs~AGE*30~
NAME*Joe~SNAME*Bloggs~AGE*30~
NAME*Joe~SNAME*Bloggs~AGE*30~
---------------------------------------
l_param[] = "";
v_name[10] =""
v_sname[10] ="";
v_age[3] = "";
char *l_cpy_string;
char *start;
char *end;
l_cpy_string = strstr(start, "NAME*");
l_cpy_string++;
while (start!=NULL)
{
strcpy(l_param, l_cpy_string);
/* Field 1*/
start = strstr(l_param, "*");
start++;
end = strstr(start, "~")
*end = '\0';
strcpy(v_name,start);
/* Field 2*/
strcpy(l_param, l_cpy_string);
start = strstr(l_param, "SNAME");
start++;
start = strstr(start, "*");
start++;
end = strstr(start, "~")
*end = '\0';
strcpy(v_sname,start);
/* Field 3*/
strcpy(l_param, l_cpy_string);
start = strstr(l_param, "AGE");
start++;
start = strstr(start, "*");
start++;
end = strstr(start, "~")
*end = '\0';
strcpy(v_age,start);
/* Perform insert into DB here using v_* variables */
/* Set ptr to next occurence of original string */
l_cpy_string = strstr(start, "NAME*");
l_cpy_string++;
--------------------------------
Cheers,
Manny
PS The string will probably have about another 5 fields that will need to be extracted - but I have not included them here as I'll just be copying and pasting the 'Field' section of the code.
-
why not have each section put into it's own string, in an array, then you only have to work through the array to insert into the database.
one thing to concider, the name fields may be to small at 10 characters, often a database name field is set to 25 characters, since some names are close to that in length.
-
Since you seem to have so many fields to extract, perhaps write a function which
- extracts the next field from a string
- returns the remainder of the string
Then you can call this function in a loop until there is no more string left.