2

I have used to split C strings by many means: strstr, strsep, strtok, strtok_r...Here is a case where I have a delimiter and I want to split the string. Having only done so in languages such as Java, JavaScript, Python..it seems verbose and clumsy. It feels a bit fragile..Is there a better way to do this? I feel that I have to put a lot of trust in arithmetic.

  char message []      = "apples are better than bananas...But good as grapes?";

  char *delimiter_location   = strstr(message, "...");
  int m1_strlen        = delimiter_location - message;
  int m1_chararr_size  = m1_strlen + 1;
  char message_1 [m1_chararr_size];
  memset(message_1, '\0', m1_chararr_size);
  strncpy(message_1, message, m1_strlen);
  printf("message: %s\n", message);
  printf("message 1: %s", message_1);
Anthony O
  • 622
  • 7
  • 26
  • 1
    `strtok` and `strsep` are the usual ways. – Barmar Sep 07 '19 at 00:22
  • 6
    C is a low-level language, everything is verbose and clumsy. – Barmar Sep 07 '19 at 00:23
  • I used to not get it when people said C is low-level, I think I get it now – Anthony O Sep 07 '19 at 01:04
  • C doesn't come with training-wheels. It will happily let you write more elements to an array than you allocate, etc... That is what makes C so blistering fast, and also what makes accurately accounting for every byte of memory used -- *The Programmer's Responsibility...*. – David C. Rankin Sep 07 '19 at 02:59

1 Answers1

1

You could use a library for regular expressions, like discussed here.

Your code can be streamlined into:

char message [] = "apples are better than bananas...But good as grapes?";

char *delimiter_location = strstr(message, "...");
int m1_strlen            = delimiter_location - message;

// Not every C standard and every compiler supports dynamically sized arrays.
// In those cases you need to use malloc() and free().
// Or even better: strdup() or strndup().
char message_1[m1_strlen + 1];
// NB no need to call memset() because the space is written to immediately:
strncpy(message_1, message, m1_strlen);
message_1[m1_strlen] = '\0'; // This ensures a terminated string.

printf("message: %s\n", message);
printf("message 1: %s\n", message_1);
the busybee
  • 10,755
  • 3
  • 13
  • 30