简体   繁体   中英

Convert Char* to array of Char*

I am trying to convert a Char* to a Char** .

eg "echo Hello World" would become {"echo", "Hello", "World"}

I know, that I can get the single words from a Char* with strtok() .

But I have problems initializing the Char** , as the Char* is of unknown size, and the single words are of unkown size as well.

Your char** is just a pointer to the first char * (or, the beginning of array of char pointers). Allocation of char*[] (it's not the same as char** !!) might be a greater problem. You should use malloc for this task. If you do not know the number of char* s in advance, you can just guess some size, fill it with NULL s and call realloc when needed.

You can run on your string and search ' ' (Space character) then each space you found you can get substring with the function strncpy to get the string between the current space index and the last space index. Each string that you create you can store on "dynamic" array (with malloc and realloc).
For the first substring your start index is 0, and at the end of the string you get the last substring between the last space index and the string length.

The first result in a Google search gives you an example that you could modify:

/* strtok example */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>        

int main ()
{
  // allocate 10 strings at a time
  int size = 10;
  int i = 0;
  char str[] ="echo Hello World";
  char** strings = malloc(size * sizeof(char*));
  char* temp;

  printf ("Splitting string \"%s\" into tokens:\n",str);
  temp = strtok (str," ");
  while (temp != NULL)
  {
    strings[i++] = temp;
    temp = strtok (NULL, " ,.-");
    if(i % size == 0)
        //allocate room for 10 more strings
        strings = realloc(strings, (i+size) * sizeof(char*));
  }

  int j;
  for(j = 0; j < i; j ++) 
  {
      printf ("%s\n",strings[j]);
  }
  return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

size_t word_count(const char *str){
    enum { out, in } status;
    size_t count = 0;
    status = out;
    while(*str){
        if(isspace(*str++)){
            status = out;
        } else if(status == out){
            status = in;
            ++count;
        }
    }
    return count;
}

int main(void){
    char original[] = "echo Hello World";
    size_t i, size = word_count(original);
    char *p, **words = (char**)malloc(sizeof(char*)*size);

    for(i = 0, p = original;NULL!=(p=strtok(p, " \t\n")); p = NULL)
        words[i++] = p;
    //check print
    printf("{ ");
    for(i = 0;i<size;++i){
        printf("\"%s\"", words[i]);
        if(i < size - 1)
            printf(", ");
    }
    printf(" }\n");

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM