J
Java and Swing
Say I have a string which contains numbers separated by a comma... such
as "0,1,2,3,4,5"...I want to split the string at the commas and return
an array containing, 0,1...5.
Suggestions? I've tried something like...
int *Split(char *msg) {
int len = 0;
char *tmp;
char *sub_string = NULL;
int *results;
tmp = (char *) malloc(strlen(msg) * sizeof(char));
strcpy(tmp, msg);
sub_string = strtok(tmp, ",");
while (sub_string != NULL) {
len++;
sub_string = strtok(NULL, ",");
}
results = (int *) malloc(len * sizeof(int));
sub_string = strtok(msg, ","); <<<<----crahses here
while (sub_string != NULL) {
*results = (int) atoi(sub_string);
results += sizeof(int);
sub_string = strtok(NULL, ",");
}
return results;
}
....above you can see I have pointed out where it crashes. I think it's
because strtok needs a pointer to the string...so I changed that line
to..
sub_string = strtok(&msg, ",");
...which got me past the error, but then when I try to print the results
after the function...it's not right. Maybe its my function or my way
of printing results.
main() {
char *msg = "1,2,3,4,5";
int *results = Split(msg);
// How do I print the results here??
}
Thanks in advance.
as "0,1,2,3,4,5"...I want to split the string at the commas and return
an array containing, 0,1...5.
Suggestions? I've tried something like...
int *Split(char *msg) {
int len = 0;
char *tmp;
char *sub_string = NULL;
int *results;
tmp = (char *) malloc(strlen(msg) * sizeof(char));
strcpy(tmp, msg);
sub_string = strtok(tmp, ",");
while (sub_string != NULL) {
len++;
sub_string = strtok(NULL, ",");
}
results = (int *) malloc(len * sizeof(int));
sub_string = strtok(msg, ","); <<<<----crahses here
while (sub_string != NULL) {
*results = (int) atoi(sub_string);
results += sizeof(int);
sub_string = strtok(NULL, ",");
}
return results;
}
....above you can see I have pointed out where it crashes. I think it's
because strtok needs a pointer to the string...so I changed that line
to..
sub_string = strtok(&msg, ",");
...which got me past the error, but then when I try to print the results
after the function...it's not right. Maybe its my function or my way
of printing results.
main() {
char *msg = "1,2,3,4,5";
int *results = Split(msg);
// How do I print the results here??
}
Thanks in advance.