我正在尝试向现有数组添加一个字符串,但我有点卡住了。我必须检查 *word 是否已经在数组中,如果不在,那么我必须将它添加到数组中。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int insert(char *word, char *Table[], int n)
{
//char *word is the string to be added, *char Table[] is array of strings
//int n is the return value, which is the number of elements in *Table[]
int counter = 0
while(*Table[counter]) //while at Index counter
{
if strcmp((*Table[counter], *word) == 0) //if *word at Index counter is true
{
return n; //return the amount of strings in the array
break; //terminate the while-loop
else
{
counter++; //increment the counter to check the next index
}
}
}
所以我希望能成功检查 *word 是否已经在数组中,但如果不在,我该如何添加呢?提前谢谢大家。
最佳答案
先从你拥有的地方开始
if strcmp((*Table[counter], *word) == 0) //if *word at Index counter is true
{
return n; //return the amount of strings in the array
break;
break
没有用,因为一旦您返回 n
函数就会停止。
其次让我们想一想,如果我们在 *Table[]
中找不到单词,那么 while 循环最终应该退出,对吗?所以我们找不到 *word
的情况是如果我们退出 while 循环
编辑:你的编译器应该提示这个函数,因为它可能你退出 while 循环然后函数不返回任何东西但是你指定它返回 int
如果你的编译器没有说你需要的任何东西打开编译器警告或使用不同的编译器。
尝试类似的东西。这是未经测试的代码,因此您可能仍需要使用它。
while(*Table[counter]) //while at Index counter
{
if strcmp((*Table[counter], *word) == 0) //if *word at Index counter is true
{
return n; //return the amount of strings in the array
break; //terminate the while-loop
else
{
counter++; //increment the counter to check the next index
}
}
*Table[counter] = *word; //Add word to the next available spot in the array
return 0;
}//End function
关于C - 将字符串添加到现有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33292917/