I am trying to remove all spaces from a string and add each word into a string array.
For instance, provided the string:
char command[120] = "apple banana orange dogfood"
an array, defined as:
char *items[20+1]; //Maximum 20 items in string + 0
would contain the elements:
{"apple", "banana", "orange" "dogfood"}
That is, all spaces have been removed.
My goal is to be able to make the call:
echo 1 3 2
and printing out
1 3 2
instead of
1 3 2
CODE
So far, I have the following:
char temp_array[120];
//Populate array with words
int i, j = 0, ant = 0;
for(i = 0; i < strlen(command); i++) {
if(isspace(command[i]) || command[i] == '\0') {
if(ant <= 20) {
temp_array[j] = '\0';
memo = (char *) malloc(sizeof(temp_array)); //allocate memory
strcpy(memo, temp_array);
items[ant] = memo;
memset(temp_array, 0, j);
ant++;
j= 0;
}
}
else if(!isspace(command[i])) {
temp_array[j] = command[i];
j++;
}
}//Done populating array
items[ant] = NULL;
Any help is highly appreciated!
char *items[20+1]is array of 21 string pointers. To define N elements of 20+1 chars, writechar items[][20+1].command? This mainly depends on wherecommandcame from and what its lifetime is through your program.strtok()andstrsep().