Parsing a String into Tokens Using strcspn, Part 2

Dave Sinkula 0 Tallied Votes 745 Views Share

This snippet is a variation of the code in Parsing a String into Tokens Using strcspn, Part 1. It uses canned strings rather than reading from a file.

See also Parsing a String into Tokens Using strcspn, Part 3.

#include <stdio.h>
#include <string.h>

int main(void)
{
   const char *line[] = { "text1|text2|text3", "text1||text3\n", "" };
   size_t j;
   for ( j = 0; j < sizeof line / sizeof *line; ++j )
   {
      const char *token = line[j]; /* point to the beginning of the line */
      printf("line %d:\n", j);
      for ( ;; )
      {
         size_t len = strcspn(token, "|\n"); /* search for delimiters */
         /*
          * Print the found text: use len with %.*s to specify field width.
          */
         printf(" -> \"%.*s\"\n", (int)len, token);
         /*
          * Instead of the above, you could use sprint to copy the text into
          * a char array.
          */
         token += len; /* advance pointer by the length of the found text */
         if ( *token == '\0' )
         {
            break; /* advanced to the terminating null character */
         }
         ++token; /* skip the delimiter */
      }
   }
   return 0;
}

/* my output
line 0:
 -> "text1"
 -> "text2"
 -> "text3"
line 1:
 -> "text1"
 -> ""
 -> "text3"
 -> ""
line 2:
 -> ""
*/