Reputation: 99
I want to split a string into several strings stored in an array (of strings). I tried to use strtok_r
, but I couldn't get that to work. So I tried doing it using this code:
int r=0;
int c=0;
for (int e=0;buf2[e]!=NULL;e++) {
if (buf2[e]!=",") {
monsters[i].types[c][r] = buf2[e];
r++;
} else {
r=0;
c++;
}
}
buf2
is the string I'm splitting, monsters[i].types[c]
is the array of strings I'm splitting it into. When I do this, it gives me:
In file included from main.c:7:0:
resource.h: In function ‘main’:
resource.h:97:22: warning: comparison between pointer and integer [enabled by default]
for (int e=0;buf2[e]!=NULL;e++) {
^
resource.h:98:14: warning: comparison between pointer and integer [enabled by default]
if (buf2[e]!=",") {
^
I tried putting the ascii values instead of NULL
& ","
, and it didn't give me any warnings, but it didn't work. And is there any way to include the two extra variable declarations before the for
into the for loop, next to the other int declaration?
Edit:
So I tried using strtok
, this is my code:
buf3 = strtok(buf2,",");
strcpy(monsters[i].types[0],buf3);
for (int e=1;buf3!=NULL;e++) {
buf3 = strtok(NULL,",");
strcpy(monsters[i].types[e],buf3);
}
This gives me a Segmentation fault (core dumped)
ReEdit:
OK, so I just needed to switch the order of setting buf3
& the strcpy
:
buf3 = strtok(buf2,",");
for (int e=0;buf3!=NULL;e++) {
strcpy(monsters[i].types[e],buf3);
buf3 = strtok(NULL,",");
}
Upvotes: 0
Views: 71
Reputation: 96966
char kDelimiter = ',';
char* start = my_string;
char* end = my_string;
char *substrings[SUBSTRINGS_MAX_NUM];
uint32_t substring_idx = 0;
uint32_t finished = 0; /* false */
do {
end = strchr(start, kDelimiter);
if (!end) {
end = my_string + strlen(my_string);
finished = 1; /* true */
}
ssize_t substring_len = end - start;
substrings[substring_idx] = NULL;
substrings[substring_idx] = malloc(substring_len + 1);
if (!substrings[substring_idx]) {
fprintf(stderr, "Error: Could not allocate space for substring!\n");
exit(EXIT_FAILURE);
}
memcpy(substrings[substring_idx], start, end - start);
substrings[substring_idx] + (end - start) = '\0';
start = end + 1;
substring_idx++;
} while (!finished);
Upvotes: 0
Reputation: 320631
Firstly, character constant syntax in C language uses single quotation marks: ','
, not ","
.
Secondly, don't compare character values to NULL
. NULL
is reserved to pointer contexts. Terminating zero character can be described as '\0'
or simply as 0
.
Thirdly, there are dedicated library functions specifically designed to simplify this task, like strtok
. I don't know though whether you can use them.
As for variable declarations, yes, you can put them all in for
as long as they all have the same type
for (int e = 0, r = 0, c = 0; ...
Note though that variables declared in this way will not be available after for
. And you will definitely need your c
after this for
.
Upvotes: 2