C - 将字符串添加到现有数组

标签 c arrays while-loop

我正在尝试向现有数组添加一个字符串,但我有点卡住了。我必须检查 *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/

相关文章:

java - 迭代器并发修改错误 (Java)

C while循环条件

c - 如何在C中将arp地址添加到/proc/net/arp

iOS UITableView 部分中的行数对同一部分使用不同的数组

c - 为什么这个结构没有正确对齐?

javascript - jQuery - 查找和删除 div 的多个属性

arrays - $SGE_TASK_ID 未通过 qsub 数组网格作业进行设置

Bash:在 while 循环内部读取

c - 快速排序无法处理小数?

c++ - 如何使用 tmpfile () 获取临时文件名