Reputation: 653
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);
Upvotes: 2
Views: 186
Reputation: 12600
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);
Upvotes: 1