c使用多个定界符分割数组

我对c很陌生,需要将“ / w / x:y /​​//// z”的char *除以“ /”或“:”分成一个char数组,这样才能得到输出“”,“ 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;

到目前为止,我已经计算出需要删除多少个字符,并且我知道我需要使用strtok。

任何帮助将不胜感激!预先谢谢你:)

since1129 回答:c使用多个定界符分割数组

这是替换字符串中的字符然后追加的简单情况。

#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);
本文链接:https://www.f2er.com/3083795.html

大家都在问