Line parsing

I have a format string "ABCDEFG, 12: 34: 56: 78: 90: 11". I want to separate these two values, separated by commas on two different lines. how to do it in gcc using c language.

+6
c string parsing
source share
6 answers

One of the possibilities is as follows:

char first[20], second[20]; scanf("%19[^,], %19[^\n]", first, second); 
+7
source share
 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.
+3
source share

So many people offer strtok ... why? strtok is the left end of the stone age of programming and is only good for 20-line utilities!

Each call to strtok modifies strToken by inserting a null character after the token returned by this call. [...] [F] unction uses a static variable to parse a string in tokens. [...] Alternating calls to this function is likely to lead to data corruption and inaccurate results.

scanf , as in the case of Jerry Coffin, is a much better alternative. Or you can do it manually: find the delimiter with strchr , then copy the parts into separate buffers.

+3
source share

You can use strtok , which allows you to specify a separator and generate tokens for you.

+1
source share

You can 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 ); } 
+1
source share

Try using the following regular expression, it will find something with the characters az AZ, and then ","

"[AZ]," if you need a lowercase letter, try "[a-zA-Z],"

If you need to search for the second part first, you can 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 of how to use REGEX at http://ddj.com/184404797

Thanks, V $ h3r

-one
source share

All Articles