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.
6 Answers
One possibility is something like this:
char first[20], second[20];
scanf("%19[^,], %19[^\n]", first, second);
1 Comment
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.
Comments
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.
5 Comments
strtok("ABCD,etc.", ",") -- i.e. passing a string literal to strtok. And strtok works by modifying the original string -- it replaces separators (',') with null characters. This is one of the reasons I wouldn't recommend strtok even to my enemy :). (The second reason being that it keeps a global state and thus not reentrant and can be not thread-safe).strtok seems good option to me.char *second = strtok(NULL, ""); to fetch the remainder of the string.You can use strtok which will allow you to specify the separator and generate the tokens for you.
Comments
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 );
}
Comments
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