Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help with string parsing which contain spaces.....

Status
Not open for further replies.

huskers

Programmer
Jan 29, 2002
75
0
0
US
I have string which I need to parse and load it into database. The string contains 7 columns and is pipe delimited and some columns might be empty spaces. For empty space I need to load them into database as null values but the problem is I can not read the nulls in C.

The string to be parsed is as follows:
1234|4324||xyz|234||asdf

Can anyone tell how I can parse this information. I tried using sscanf() and strtok() but they ignore the null values.

I do not want to traverse through the whole string as there are millions of records and it might slow things down. Is there any efficent way of doing this.


Thanks
 
[tt]sscanf[/tt] seems to do okay for me.
Code:
#include<stdio.h>

int main(void)
{
   size_t i;
   char field [ 7 ] [ 20 ];
   const char text[] = "1234|4324||xyz|234||asdf", *ptr = text;
   int n = 0;
   for ( i = 0; i < sizeof field / sizeof *field; ++i )
   {
      if ( sscanf(ptr, "%19[^|]%n%*c", field[i], &n) == 1 )
      {
         ptr += n + 1;
      }
      else
      {
         field[i][0] = '\0';
         ++ptr;
      }
   }
   for ( i = 0; i < sizeof field / sizeof *field; ++i )
   {
      printf("field[%lu] = \"%s\"\n", (long unsigned)i, field[i]);
   }
   return 0;
}

/* my output
field[0] = "1234"
field[1] = "4324"
field[2] = ""
field[3] = "xyz"
field[4] = "234"
field[5] = ""
field[6] = "asdf"
*/
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top