将字符串中的每个单词放入C中的数组中

时间:2014-10-14 22:20:48

标签: c arrays strtok

我试图将一个字符串(由用户在运行时键入)分成单词(用空格分隔),然后将每个单词放入一个不同的插槽中。因此,例如,如果我使用字符串"hello world"array[0]将包含"hello"array[1]将包含"world"。最后一个广告位(在本例中为array[2])将包含NULL。这是我到目前为止所做的,似乎没有正常工作。任何帮助,将不胜感激。 (顺便说一句,这是一个会调用execvp(argv[0],argv);

的程序的一部分
char input[100];
char* argv[20];
char* token;
scanf("%s", input);

//get the first token
token = strtok(input, " ");

int i=0;
//walk through other tokens
while( token != NULL ) {
    argv[i] = token;
    i++;
    token = strtok(NULL, " ");
    } 
argv[i] = NULL; //argv ends with NULL

3 个答案:

答案 0 :(得分:3)

您需要为每个argv [i]分配内存并将当前令牌复制到argv [i]:

token = strtok(input, " ");

int i=0;
//walk through other tokens
while( token != NULL ) {
    argv[i] = malloc(strlen(token) + 1);
    strncpy(argv[i], token, strlen(token));
    //argv[i] = token;
    i++;
    token = strtok(NULL, " ");
    } 
argv[i] = NULL; //argv ends with NULL

答案 1 :(得分:0)

我已经创建了一个我认为你想要的例子。我整体上使用了一个malloc(3) 字符串和另一个字符串,用于从函数中获取的指针数组。

此外,传递strtok(3)的第二个参数以提供更大的灵活性(shell通常使用IFS环境变量的内容来分隔参数,因此您可以使用与shell相同的算法)我认为您应该至少使用" \n\t"。它具有main()测试功能,所以它完全符合您的目的。

#include <assert.h> /* man assert(3) */
#include <stdlib.h> /* malloc lives here */
#include <string.h> /* strtok, strdup lives here */
#include <stdio.h> /* printf lives here */

char **split(const char *str, const char *delim)
{
    char *aux;
    char *p;
    char **res;
    char *argv[200]; /* place for 200 words. */
    int n = 0, i;

    assert(aux = strdup(str));
    for (p = strtok(aux, delim); p; p = strtok(NULL, delim))
        argv[n++] = p;
    argv[n++] = NULL;
    /* i'll put de strdup()ed string one place past the NULL,
     * so you can free(3), once finished */
    argv[n++] = aux;
    /* now, we need to copy the array, so we can use it outside
     * this function. */
    assert(res = calloc(n, sizeof (char *)));
    for (i = 0; i < n; i++)
        res[i] = argv[i];
    return res;
} /* split */

int main()
{
    char **argv =
        split("Put each word of a string into array in C", " ");
    int i;

    for (i = 0; argv[i]; i++)
        printf("[%s]", argv[i]);
    puts("");  /* to end with a newline */

    free(argv[i+1]);
    free(argv);
} /* main */

示例代码只输出:

$ pru
[Put][each][word][of][a][string][into][array][in][C]

答案 2 :(得分:-1)

我想我只是想出了我的问题:我需要使用gets()而不是scanf(),因为scanf()只获取第一个单词,直到空格,而我希望能够得到一个字符串包含由空格分隔的多个单词。

相关问题