【问题标题】:How to add words from a string to an array of strings in c如何将字符串中的单词添加到c中的字符串数组中
【发布时间】:2021-03-30 16:08:23
【问题描述】:

我有一个字符串,比如说char input[] = "one two three";,我想要的是一个函数,它接受两个参数,输入字符串和我想要这些词所在的字符串数组。

例如,在伪代码中,transferWords(input, words) 将获取input 字符串中的每个单词并将其放入字符串数组words 中,这样words = {"one", "two", "three"}。我无法分配内存(malloc() 等...),因为练习不允许我这样做。

我尝试过使用指针,但这没有用,因为如果我碰巧访问单词[21],它将读取其他内容:

void transfer(char input[], char *words[20]){

    char *p;
    int i = 0;

    p = strtok(input," \t\n");

    while(p != 0)
    {
        words[i++] = p;
        p = strtok(0, " \t\n");
    }
}

words 之前将被初始化为 char *words[20] = {0};

我该怎么做呢?

(我对 C 语言还很陌生,还不太习惯,所以如果这是显而易见的事情,请道歉。)

【问题讨论】:

  • 如果没有 malloc 或 C99 的 VLA,您将需要字符串数组的最大大小。

标签: arrays c string


【解决方案1】:

如果您无法调整数组的大小,则必须在开始时以适当的大小分配它们。对于任何输入数组a,最大字数为(n/2)+1,其中n 是a 中的字符数。然后我们知道任何单词的最大大小是n,因为我们可以有一个只有一个单词的输入字符串。如果你用这个大小声明你的 words 数组,你可以保证任何输入都可以捕获所有的单词。在许多情况下,您会浪费一些(或大量)空间,但您会保证可以存储所有可能的单词。我不确定分配是如何预先完成的,但请参阅以下代码以获得一般描述。

int n;
//Get first the size of the input array...
scanf("%d", n);

//Now we need to get the entire input and allocate our arrays
char input[n + 1]; //plus one for the null terminator if we need it
char words[(n/2) + 1][n + 1]; //(n/2) + 1 max words with a max size of n for each 
//plus one on n for the null terminator

//get input...
fgets(input, n, stdin);

//Now you can run your function

执行此操作的一般更直观的方法是使用 mallocrealloc 动态增长您的数组,这样您就不会浪费太多空间,但是由于您明确表示您不能这样做,所以这也可以并将保证使用的空间最少,同时保证可以存储所有可能的单词组合。

然后,要将字符串从输入移动到 words 数组,请使用 strcpy 将各个单词复制到 words 数组。

void transfer(char *input, char **words){

    char *p;
    int i = 0;

    p = strtok(input," \t\n");

    while(p != NULL)
    {
        strcpy(words[i++], p);
        p = strtok(NULL, " \t\n");
    }
}

【讨论】:

    【解决方案2】:

    作为提示,给你的函数和参数命名更有意义。

    例如:

    /*
    * Breaks the string str into words (delimited by whitespace) 
    * and stores them in the array words.
    *
    * @param str a null-terminated string, must not be NULL
    * @param words an array of char pointers, must not be NULL
    * @param length the size of the array words, must be >0
    *
    * @return returns the number of words in the string
    */
    int split(char *str, char *words[], unsigned length)
    {
        int i=0;
    
        for (; i < length; ++i, str = NULL) {
            words[i] = strtok(str, "\r\n\t\f ");
            if (words[i] == NULL)
                break;
        }
    
        return i;
    }
    
    int main()
    {
        #define N 20
        char *words[N];
    
        char *input = strdup("one two three");
    
        int num = split(input, words, N);
        printf("%d\n", num);
    
        free(input);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2015-03-09
      • 1970-01-01
      • 2023-01-19
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      相关资源
      最近更新 更多