[英]How to add words from a string to an array of strings in c
我所拥有的是一个字符串,比如说char input[] = "one two three";
我想要的是一个 function,它接收两个 arguments、输入字符串和我希望这些单词所在的字符串数组。
例如,在伪代码中, transferWords(input, words)
将获取input
字符串中的每个单词并将其放入字符串数组words
中,这样words = {"one", "two", "three"}
。 我无法分配 memory ( malloc()
等...)来执行此操作,因为练习不允许我这样做。
我尝试过的是使用指针,但这没有用,因为如果我碰巧访问 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");
}
}
其中words
将被初始化为char *words[20] = {0};
前。
我怎么能 go 这样做呢?
(我对 C 还是很陌生,而且我还不太习惯,所以如果这很明显,请道歉。)
如果您无法调整 arrays 的大小,则必须在开始时分配适当的大小。 对于任何输入数组 a,最大字数为(n/2)+1
,其中n
是 a 中的字符数。 然后我们知道任何单词的最大大小是n
,因为我们可以有一个只有一个单词的输入字符串。 如果你用这个大小声明你的单词数组,你可以保证任何输入都可以捕获所有单词。 在许多情况下,您会浪费一些(或大量)空间,但您会保证可以存储所有可能的单词。 我不确定分配是如何事先完成的,但请参阅以下代码以获得一般描述。
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
执行此操作的一般更直观的方法是使用malloc
和realloc
来动态增长您的数组,这样您就不会浪费太多空间,但是由于您明确表示您不能这样做,所以这也可以正常工作,并保证最少的在保证可以存储所有可能的单词组合的同时使用的空间。
然后,要将字符串从输入移动到 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");
}
}
作为提示,将您的函数和参数命名为更有意义。
例如:
/*
* 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.