简体   繁体   English

如何将字符串中的单词添加到 c 中的字符串数组中

[英]How to add words from a string to an array of strings in c

What I have is a string, let's say char input[] = "one two three";我所拥有的是一个字符串,比如说char input[] = "one two three"; and what I want is a function that takes in two arguments, the input string and an array of strings where I want those words to be.我想要的是一个 function,它接收两个 arguments、输入字符串和我希望这些单词所在的字符串数组。

For example, in pseudo code, transferWords(input, words) would take every word in the input string and put it in the string array words so that words = {"one", "two", "three"} .例如,在伪代码中, transferWords(input, words)将获取input字符串中的每个单词并将其放入字符串数组words中,这样words = {"one", "two", "three"} I can't allocate memory ( malloc() , etc...) to do this since the exercise does not allow me to.我无法分配 memory ( malloc()等...)来执行此操作,因为练习不允许我这样做。

What I've tried is using pointers but this isn't useful because if I happen to access words[21] it would be reading something else:我尝试过的是使用指针,但这没有用,因为如果我碰巧访问 words[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");
    }
}

where words would be initalized as char *words[20] = {0};其中words将被初始化为char *words[20] = {0}; before.前。

How could I go about doing this?我怎么能 go 这样做呢?

(I am still pretty new to C and I'm not very used to it yet, so apologies if this is something obvious.) (我对 C 还是很陌生,而且我还不太习惯,所以如果这很明显,请道歉。)

If you are not able to resize your arrays, you must allocate them initially with the proper size.如果您无法调整 arrays 的大小,则必须在开始时分配适当的大小。 For any input array a, the max number of words is (n/2)+1 , where n is the number of characters in a.对于任何输入数组 a,最大字数为(n/2)+1 ,其中n是 a 中的字符数。 We then know the max size of any word is n , as we could have an input string with only one word.然后我们知道任何单词的最大大小是n ,因为我们可以有一个只有一个单词的输入字符串。 If you declare your words array with this size, you can guarantee for any input you can capture all the words.如果你用这个大小声明你的单词数组,你可以保证任何输入都可以捕获所有单词。 You will, in many cases, waste some (or a lot) of space, but you will guarantee all possible words can be stored.在许多情况下,您会浪费一些(或大量)空间,但您会保证可以存储所有可能的单词。 I'm not sure how the allocation is done before hand, but see the following code for a general description.我不确定分配是如何事先完成的,但请参阅以下代码以获得一般描述。

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

The general more intutive way of doing this is using malloc and realloc to dynamically grow your array so you don't waste so much space, but since you explicitly said you cannot do this, this will work as well and will guarantee the minimum amount of space used while guaranteeing all possible combination of words can be stored.执行此操作的一般更直观的方法是使用mallocrealloc来动态增长您的数组,这样您就不会浪费太多空间,但是由于您明确表示您不能这样做,所以这也可以正常工作,并保证最少的在保证可以存储所有可能的单词组合的同时使用的空间。

Then, to move the strings from the input to the words array, use strcpy to copy the individual words to the words array.然后,要将字符串从输入移动到 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");
    }
}

As a hint, name your functions and parameters more meaningful.作为提示,将您的函数和参数命名为更有意义。

For Example:例如:

/*
* 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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