Home > database >  How can I add a string to an array of strings in C?
How can I add a string to an array of strings in C?

Time:11-20

I have a string "token" and an empty array of strings "arr". I want to add token to the first index of arr. I've tried arr[0][0] = token, but this would only work for chars and I've also tried arr[0] = token but this throws the error "expression must be a modifiable lvalue". My full program is:

#include <stdio.h>
#include <string.h>

char arr[100][100] = {};
char *token = strtok(StringToBeSplit, " ");
int i = 0;

while(token != NULL) {
    arr[0] = token;
    printf("%s\n", token);
    token = strtok(NULL, " ");
    i  ;
}

What should I do?

CodePudding user response:

You need to copy the string instead of assigning it. The other problem with your code is that only element [0] of the array ever gets populated

#include <stdio.h>
#include <string.h>

char arr[100][100] = {};
char *token = strtok("split this string", " ");
int i = 0;

while(token != NULL) {
    strcpy(arr[i], token);
    printf("%s\n", token);
    token = strtok(NULL, " ");
    i  ;
}

// At this point, i contains the number of tokens.

If you started i at -1 and incremented before the strcpy, then i would be the index of the last element.

CodePudding user response:

You need to avoid assigning string literal to strtok. Basically using strcpy to copy the token to array and increment array as advised by previous answer. Something like this:-

#include <stdio.h>
#include <string.h>

int main(){

char arr[100][100] = {};
char str[] = "Split this string";
char sep[] = " ";
char *token = strtok(str, sep);
int i = 0;
while(token != NULL){
    strcpy(arr[i], token);
    token = strtok(NULL, sep);
    i  ;
}

//Test If it can print the strings
for(int j = 0; j < i; j  )
    printf("%s\n", arr[j]);

 }
  • Related