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 :)

6
  • 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? Commented Nov 18, 2019 at 3:27
  • Sorry my bad! I've updated it. Thanks for pointing that out Commented Nov 18, 2019 at 3: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? Commented Nov 18, 2019 at 3:33
  • Yes that is correct, it says on my specification it needs to have at least 1 NULL at the end. Commented Nov 18, 2019 at 3: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. Commented Nov 18, 2019 at 3:39

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.