1

I'm very new to c and need to split a char* of "/w/x:y////z" by "/" or ":" into an array of char so would get an output of "", "w", "x", "y","", "", "", "", "z", NULL

int i;
int j;
int len = strlen(self);
int l = strlen(delim);
int cont;
int count = 0;   
char* self = {"/w/x:y////z"};
char* delim = {"/:"};

for (j = 0; j < l; j++) {
    for (i = 0; i < len; i++) {
        if (self[i] == delim[j]) {
            count +=1;
        }
    }
}

count += 1;

So far I have worked out how many characters need to be removed and I know I need to use strtok.

Any help would be much appreciated! Thank you in advance :)

Tudders
  • 53
  • 8
  • 1
    Your expected output is a bit confusing. It looks like you want to replace the delimiters with `\0`, but then you also actually remove a slash and don't replace it. Could you specify a bit more? – Frontear Nov 18 '19 at 03:27
  • Sorry my bad! I've updated it. Thanks for pointing that out – Tudders Nov 18 '19 at 03:30
  • So, to clarify, you simply want to replace your delimiters with empty characters, and append a NULL to the end of the string? Any reason for the NULL? – Frontear Nov 18 '19 at 03:33
  • Yes that is correct, it says on my specification it needs to have at least 1 NULL at the end. – Tudders Nov 18 '19 at 03:36
  • You should create a character array of `strlen(self) + 1`, then just iterate over `self`, find which characters match your delimiters and which don't, and simply replace accordingly. Afterwards, append to the final element, a `NULL`. – Frontear Nov 18 '19 at 03:39
  • `strsep` is the way to split a string on a delimiter preserving empty-fields. Your other two options are to use `strcspn` and `strspn`, or finally, just walk a pair of pointers down your string parsing manually as you go. – David C. Rankin Nov 18 '19 at 03:41

1 Answers1

1

This is a simple case of replacing the characters in a string, and then appending.

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

// ...

const char* self = "/w/x:y////z";
const char* replace = "/:"; // either of them

const int self_len = strlen(self);
const int replace_len = strlen(replace);

char string[self_len + 1]; // + 1 for the NULL at the end

// -- example implementation
for (int i = 0; i < self_len; ++i) {
    bool delim = false;
    for (int j = 0; j < replace_len; ++j) {
        if (self[i] == replace[j]) {
            string[i] = ' '; // whatever replacement you want here
            delim = true;

            break;
        }
    }

    if (!delim) {
        string[i] = self[i];
    }
}
// -- example implementation

string[self_len] = NULL; // appending at the end

printf("%s\n", string);
Frontear
  • 1,150
  • 12
  • 25
  • Make sure that is actually doing what you need it to. It's not separating individual tokens into an array if that is your goal. – David C. Rankin Nov 18 '19 at 03:51