c - C 中的字符串数组搜索

标签 c arrays string

我试图弄清楚如何搜索输入到字符串数组中的名称列表。如果输入的名称是原始数组的一部分,则搜索函数应返回该字符串在数组中的位置;如果未找到该字符串,则应返回 -1。如果返回-1,那么我希望能够打印出“未找到”,这似乎不太难弄清楚,但是如果找到了名称,我希望能够打印出找到名称的位置。

这是我的代码,显然我对此很陌生,所以我可能已经破坏了这应该如何完成。我的其余代码似乎工作正常,但正是这个函数让我不知所措。

#include<stdio.h>
#include<conio.h>
#include<string.h>

#define MAX_NAMELENGTH 10
#define MAX_NAMES 5
void initialize(char names[MAX_NAMES][MAX_NAMELENGTH]);
int search(char names[MAX_NAMES][MAX_NAMELENGTH],int i,Number_entrys);
int main()
{
    char names[MAX_NAMES][MAX_NAMELENGTH];
    int i;
    initialize(names);
    search(names,i,Number_entrys);
    search_result= search(names,i,Number_entrys);
    if (search_result==-1){
        printf("Found no names.\n");
    }
    if(search_result==0){
       printf("Name found");
    }    getch();
    return 0;
}

void initialize(char names[MAX_NAMES][MAX_NAMELENGTH])
{
    int i, Number_entrys;

    printf("How many names would you like to enter to the list?\n");
    scanf("%d",&Number_entrys);

    if(Number_entrys>MAX_NAMES){
               printf("Please choose a smaller entry\n");
    }else{
        for (i=0; i<Number_entrys;i++){
            scanf("%s",names[i]);
        }
    }
    for(i=0;i<Number_entrys;i++){

        printf("%s\n",names[i]); 
    }
}

int search(char names[MAX_NAMES][MAX_NAMELENGTH],int i)
{
    int j, idx;
    char name[MAX_NAMELENGTH];
    printf("Now enter a name in which you would like to search the list for:");
    scanf("%s", name);

    for(x = 0; x < Number_entrys; x++) {
        if ( strcmp( new_name, names[x] ) == 0 ){
            /* match, x is the index */
            return x;
        }else{
            return -1;   
        }
    }
}

最佳答案

这里有几个问题。

搜索的目的是要求用户输入要搜索的单个名称。那么为什么是

 char new_name[MAX_NAMES][MAX_NAMELENGTH];

您只需要一个数组

 char new_name[MAX_NAMELENGTH];

然后你就有了一个循环,只需循环一次,所以你不需要循环

 scanf("%s",new_name);

就足够了。这感觉就像您复制了用于填充名称数组的代码,但尚未真正理解其本质。

另一个问题是您无法控制用户可能输入的名称的长度。如果用户输入很长的名称会发生​​什么?如果你的数组填满了,你的程序可能会崩溃并烧毁。阅读 this article了解如何控制它。

要真正迂腐,您还应该检查 scanf 的返回代码,您希望读取一项,因此返回值应该为 1,其他任何值都会出错。

然后您尝试使用 strstr() 来查看 char 数组的数组。 strstr documentation说它的目的是搜索字符串中的子字符串,而不是搜索字符串数组。

所以只需手动搜索数组即可

/* what is i? the number of items used in the array? */
for(x = 0; x < i; x++) {
    if ( strcmp( new_name, names[x] ) == 0 ){
        /* match, x is the index */
        return x;
    }
}
/* here with no match */
return -1;

在你的主目录

int 搜索结果;

search_result = search( /* etc */ );

if ( search_result == -1 ) {
     /* print "not found" here */
} else {
     /* print something else */
}

关于c - C 中的字符串数组搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13105903/

相关文章:

c - 如何在 C 中隐藏结构的某些字段?

PHP - 如何按总和值对这个多维数组进行排序?

arrays - 使用 Array.map 在字典数组中搜索

java - 如何使用 Java 标准 API 从字符串中获取特定数据?

c++ - 在 DLL 中的哪里调用 LoadLibrary?

c++ - 关于linux shell函数与C函数的关系()

c - 如何使用 C 转储 PE 导出函数名称?

string - 查找两个变量名标量的并集

C++ Clean String to int 转换

java - 拆分字符串方法的奇怪行为