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.
One possibility is something like this:
char first[20], second[20];
scanf("%19[^,], %19[^\n]", first, second);
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.
You can use strtok which will allow you to specify the separator and generate the tokens for you.
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 );
}
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.
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