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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How To Split Value From Delimiter.

Status
Not open for further replies.

itlike

MIS
Oct 18, 2002
4
0
0
MY
How to split 'cookie' by seperating the delimiter '|' ?

cookie="item 1 : desc2 | item2 : desc2";

Assume the value of 'cookie' is not fix. I want use the
while loop to display each item where the format is
separated by "|".

Eg. my expected output as below :

item item desc
----- ---------
item1 desc1
item2 desc2

Please help. Thank.
 
You could use the strtok()function.

char cookie[1024];
char * ptok;
strcpy(cookie, source_of_cookie);
ptok = strtok(cookie, "|");
while(ptok) {
printf("\n%s", ptok);
ptok = strtok(0, "|");
}

This will produce something like this
cookie="item 1 : desc2
item2 : desc2";

To get rid of <cookie=&quot;> call 1. strtok with parameter cookie + xx instead of just cookie.
/JOlesen
 
I,

my post may be not appropriate in this forum, the right
has done already JOLESEN.

If you are working at a Unix env you don't need to write
a c-program only for this purpose.

Using &quot;awk&quot; command line ( FS='|')you will have this and more possibilities.
AWK is not a simple command but in pratic a programming Language: it is intepreted.

The details are out of the scope of forum, but if you need
post again.

bye
 
Hello JOlesen,

I almost done on my part. Thank you very much for
your help.

I got another problem. How to split again item1
and desc1 seperately by &quot;:&quot; delimiter ? I had tried
to use sscanf(), but it never work.

I may think if my desc or item got space (eg &quot;item 1&quot;),
sscanf will never work. But without space (eg &quot;item1&quot;), the
program will work accordingly. My description definately
got space in between.

Please help.

==== my program =====
char cookie[1024];
char item[50],desc[50]
char * ptok;
strcpy(cookie, &quot;item 1: desc 1 | item 2: desc 2&quot;);
ptok = strtok(cookie, &quot;|&quot;);
while(ptok) {
sscanf(ptok,&quot;%s:%s&quot;, item, desc);
printf(&quot;\n%s == %s&quot;, item, desc);
ptok = strtok(0, &quot;|&quot;);
}

 
You are right : sscanf is not really good for this.

You could use strchr() to find/locate the ':'.
If ':' is found, copy what's located between ptok and ':' to variable item . Also copy whats located *after* ':' to desc.
/JOlesen
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top