sfactor
sfactor

Reputation: 13062

Parsing a string

i have a string of the format "ABCDEFG,12:34:56:78:90:11". i want to separate these two values that are separated by commas into two different strings. how do i do that in gcc using c language.

Upvotes: 6

Views: 620

Answers (6)

Vsh3r
Vsh3r

Reputation: 11

Try using the following regex it will find anything with chars a-z A-Z followed by a ","

"[A-Z]," if you need lower case letter too try "[a-zA-Z],"

If you need it to search for the second part first you could try the following

",[0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{2}"

There is an example on how to use REGEX's at http://ddj.com/184404797

Thanks, V$h3r

Upvotes: -1

N 1.1
N 1.1

Reputation: 12524

char str[] = "ABCDEFG,12:34:56:78:90:11"; //[1]

char *first = strtok(str, ",");  //[2]
char *second = strtok(NULL, "");  //[3]

[1]  ABCDEFG,12:34:56:78:90:11  

[2]  ABCDEFG\012:34:56:78:90:11
     Comma replaced with null character with first pointing to 'A'

[3]  Subsequent calls to `strtok` have NULL` as first argument.
     You can change the delimiter though.

Note: you cannot use "string literals", because `strtok` modifies the string.

Upvotes: 3

atzz
atzz

Reputation: 18010

So many people are suggesting strtok... Why? strtok is a left-over of stone age of programming and is good only for 20-line utilities!

Each call to strtok modifies strToken by inserting a null character after the token returned by that call. [...] [F]unction uses a static variable for parsing the string into tokens. [...] Interleaving calls to this function is highly likely to produce data corruption and inaccurate results.

scanf, as in Jerry Coffin's answer, is a much better alternative. Or, you can do it manually: find the separator with strchr, then copy parts to separate buffers.

Upvotes: 3

ChronoPositron
ChronoPositron

Reputation: 1518

You could use strtok:

Example from cppreference.com:

 char str[] = "now # is the time for all # good men to come to the # aid of their country";
 char delims[] = "#";
 char *result = NULL;
 result = strtok( str, delims );
 while( result != NULL ) {
     printf( "result is \"%s\"\n", result );
     result = strtok( NULL, delims );
 }

Upvotes: 1

nevets1219
nevets1219

Reputation: 7706

You can use strtok which will allow you to specify the separator and generate the tokens for you.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490128

One possibility is something like this:

char first[20], second[20];

scanf("%19[^,], %19[^\n]", first, second);

Upvotes: 7

Related Questions