简体   繁体   中英

c split an array using multiple delimiters

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM