RGIII RGIII - 1 month ago 4x
C Question

How do I store my substring between strtok tokens in C?

Basically, I'm using strtok() to get rid of extra subsequent whitespace, then using strcat() to concatenate the string back so there's only one white space in the string as required.
For example:
"hello there." string has 3 whitespaces. My program will successfully strtok() the string and then put it back together, so to speak, with just one whitespace. However, when the string looks like this:
"hello there how are you?" my program will output: "hello you", discarding everything in between the tokens.

Here's the snippet of my code:

void stringFunction(struct dh *header){
int i;
char *spaceTk, *spaceString, *holder;
struct dh *temp;

temp = header->next;
while(temp != NULL){
spaceString = malloc(strlen(temp->string)+1);
strcpy(spaceString, temp->string);

for(i=0; i<strlen(spaceString) +1; i++){
if(spaceString[i] == ' '){
count++; //don't worry about this variable
if(spaceString[i] == ' ' && spaceString[i+1] == ' '){
spaceTk = strtok(spaceString, " ");
while(spaceTk != NULL){
holder = malloc(strlen(spaceTk)+1);
strcpy(holder, spaceTk);
spaceTk = strtok(NULL, " ");
strcat(spaceString, " ");
strcat(spaceString, holder);
strcpy(temp->string, spaceString);


I understand that the variable "holder" stores the tokens, but is overwritten by the very last one. I'm just unsure how to save the words in between the first and last tokens.

Thank you.



char *holders[MAX_STRINGS];
int k= 0;
while(spaceTk != NULL && k<MAX_STRINGS){
    holders[k] = malloc(strlen(spaceTk)+1);
    strcpy(holders[k], spaceTk);
    spaceTk = strtok(NULL, " ");