Reputation: 53
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 :)
Upvotes: 1
Views: 160
Reputation: 1261
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);
Upvotes: 1