Duzzz
Duzzz

Reputation: 191

C splitting string to stringarray

I am trying to make a metod that takes a string and an array and splits the string into array of strings using strtok(). I assume the given array has enough room and splitting is made when there is a space in array. I think this is almost correct, I just need the last push :) Here is my code atm:

string_to_stringarray(char* string, char** array) {

    int i = 0;
    array[i] = strtok(string, " ");

    while (array != NULL) {
        array[i++] = strtok(NULL, " ");
    }
}

Upvotes: 1

Views: 168

Answers (4)

Duzzz
Duzzz

Reputation: 191

So the solution was obvious, I missed [i] in while loop. The correct line being

while (array[i] != NULL){

Thanks for quick answers :) Going to bed now since I am not making any progress lol

Upvotes: 0

Zach Thompson
Zach Thompson

Reputation: 39

I've done something similar with the shell I'm essentially finished building in C++, except I used a vector as a queue instead of an array. Maybe you can bounce off of my algorithm that I've already proven to work.

    int i = inputString.find_first_not_of(" ");
    int j = inputString.find_last_not_of(" \n\r");
    int k;
    string stringToAdd;

    while (i != -1) {
            k = i;

            while (inputString.at(k) != ' ') {

                    if (k == j) {
                            break;
                    };

                    k++;
            };

            if (k != j) {
                    k--;
            };

            stringToAdd = inputString.substr(i, k - i + 1);
            i = inputString.find_first_not_of(" ", k + 1);
            commandQueue.push_back(stringToAdd);
    };

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

The condition in the while statement

while (array != NULL) {
       ^^^^^^^^^^^^^

is wrong because the array as it follows from your post is already allocated.

The function can look like

void string_to_stringarray( char *string, char **array ) 
{
    int i = 0;

    array[i] = strtok( string, " " );

    while ( array[i] != NULL ) array[++i] = strtok( NULL, " " );
                                   ^^^
}

Upvotes: 0

unwind
unwind

Reputation: 400109

The while condition makes no sense. The value of array doesn't change in the function, so the loop is infinite (unless array is NULL from the beginning, in which case the first assignment to array[0] causes undefined behavior).

It should be something like:

size_t split_string(char *string, char **array) {
  size_t i = 0;

  char *token = strtok(string, " ");
  while (token != NULL)
  {
    array[i++] = token;
    token = strtok(NULL, " ");
  }
  return i;
}

This returns the number of strings found, and changes the name since user code can't define functions beginning with str.

Upvotes: 2

Related Questions