We help IT Professionals succeed at work.

Seperation using delimiters

singhtaj
singhtaj asked
on
Medium Priority
394 Views
Last Modified: 2010-04-15
Hi,

If I have a string like
"ABC_DEF_123"

How would I seperate the three of them ?
what I want is the three of them seperated for example
after seperation :
temp1 will contain "ABC"
temp2 will contain "DEF"
and temp3 will contain "123"

How would I do this ? I tried using standard stuff but still
am unsuccessful ...

Any help will be appreciated.
Thanks
Comment
Watch Question

Use strtok inside a loop:

The first call is done outside the loop when the first param is the string you want to parse.
Then you just loop for as long it returns something, whith the first parameter set to NULL

Commented:
Another option is to use scanf() with sets ([...] and [^...]).

Author

Commented:
How do I use strtok in this case ? I tried but am unsuccessful...

Author

Commented:
How do I use strtok in this case ? I tried but am unsuccessful...

ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
#include <string.h>

char *string="ABC_DEF_123";
char *temp1,*temp2,*temp3;
temp1=strtok(string,"_");
temp2=strtok(0,"_");
temp3=strtok(0,"_");
printf("trmp1=%s, trmp2=%s, temp3=%s;\n",temp1,temp2,temp3);

Author

Commented:
How do I use strtok in this case ? I tried but am unsuccessful...

ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
/*Another option is to use*/
char tmp1[100],tmp2[100],tmp3[100];
sscanf("ABC_DEF_123","%99[^_]_%99[^_]_%99[^_]",tmp1,tmp2,tmp3);
printf("tmp1=%s, tmp2=%s, tmp3=%s;\n",tmp1,tmp2,tmp3);

Author

Commented:
ozo your "sscanf" solution is not working !!!
I wonder what is wrong with it ???
Basically the strings printed out have nothing in them...
Any ideas ???

ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
it should work.  what does your code look like?

Author

Commented:
Okay I am sorry!!!

Its working. It was my error internally.
Now How do I grade you ? Because Now I don't have any options
of giving you the grade ?

Author

Commented:
By the way ozo, is it possible to scan the last item "123"
to be an integer ?

That is instead of char tmp3[100] being "123"
i want int tmp3=123 ?

Is this possible using sscanf ?


CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks for the help

Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.